diff --git a/Directory.Packages.props b/Directory.Packages.props index e22e17c7..ba673043 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -68,6 +68,7 @@ + diff --git a/docs/technical/api/library/audio-library/music-library/Api.Albums.md b/docs/technical/api/library/audio-library/music-library/Api.Albums.md index 0a08db52..21459643 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Albums.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Albums.md @@ -41,6 +41,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "title": "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.", + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -49,10 +50,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "releaseCountry": "GB", "releaseVersion": "Remastered" }, - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, "language": { "languageCode": "en", "languageName": "English", @@ -63,18 +60,27 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "vinyl" } - ] + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -103,12 +109,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "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.", - "durationInSeconds": 354, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 980, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -127,24 +128,50 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "epic" } - ] + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "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" } @@ -162,13 +189,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "source": "LastFm", "voteCount": 1234 } - ], - "moods": [ - { "name": "dramatic" }, - { "name": "anxious" } - ], - "isrcs": [ - { "value": "GBUM71029604" } ] }, { @@ -177,12 +197,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "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.", - "durationInSeconds": 181, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 912, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, @@ -201,24 +216,50 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "love" } + ], "genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "love" } - ] + "isVideo": false, + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "moods": [ + { "name": "happy" }, + { "name": "warm" } + ], + "isrcs": [ + { "value": "GBUM71029609" } + ], "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } @@ -236,13 +277,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "source": "LastFm", "voteCount": 567 } - ], - "moods": [ - { "name": "happy" }, - { "name": "warm" } - ], - "isrcs": [ - { "value": "GBUM71029609" } ] } ] @@ -264,10 +298,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "title": "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.", - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -286,26 +317,27 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "languageName": "English", "nativeName": "English" }, - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], "tags": [ - { - "name": "classic" - }, - { - "name": "vinyl" - } - ] + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -345,50 +377,50 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "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.", - "releaseInfo": { - "originalReleaseDate": "1975-10-31", - "originalReleaseYear": 1975, - "reReleaseDate": null, - "reReleaseYear": null, - "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" } - ], + "disambiguation": null, + "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "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 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, + "moods": [ + { "name": "dramatic" }, + { "name": "anxious" } + ], + "isrcs": [ + { "value": "GBUM71029604" } + ], "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", @@ -412,13 +444,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "source": "LastFm", "voteCount": 1234 } - ], - "moods": [ - { "name": "dramatic" }, - { "name": "anxious" } - ], - "isrcs": [ - { "value": "GBUM71029604" } ] }, { @@ -430,50 +455,50 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "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.", - "releaseInfo": { - "originalReleaseDate": "1976-06-18", - "originalReleaseYear": 1976, - "reReleaseDate": null, - "reReleaseYear": null, - "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" } - ], + "disambiguation": null, + "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "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 + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, + "moods": [ + { "name": "happy" }, + { "name": "warm" } + ], + "isrcs": [ + { "value": "GBUM71029609" } + ], "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", @@ -497,13 +522,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "source": "LastFm", "voteCount": 567 } - ], - "moods": [ - { "name": "happy" }, - { "name": "warm" } - ], - "isrcs": [ - { "value": "GBUM71029609" } ] } ] @@ -535,10 +553,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "title": "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.", - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -557,26 +572,27 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "languageName": "English", "nativeName": "English" }, - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], "tags": [ - { - "name": "classic" - }, - { - "name": "vinyl" - } - ] + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -671,10 +687,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "title": "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.", - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -693,26 +706,27 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "languageName": "English", "nativeName": "English" }, - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], "tags": [ - { - "name": "classic" - }, - { - "name": "vinyl" - } - ] + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -761,6 +775,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "title": "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.", + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -769,10 +784,6 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "releaseCountry": "GB", "releaseVersion": "Remastered" }, - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, "language": { "languageCode": "en", "languageName": "English", @@ -783,18 +794,27 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "vinyl" } - ] + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -834,10 +854,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "title": "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.", - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -856,26 +873,27 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "languageName": "English", "nativeName": "English" }, - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], "tags": [ - { - "name": "classic" - }, - { - "name": "vinyl" - } - ] + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -948,27 +966,41 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "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 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, "moods": [ @@ -1048,7 +1080,3 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "numberOfPages": 1 } ``` - - - - diff --git a/docs/technical/api/library/audio-library/music-library/Api.Artists.md b/docs/technical/api/library/audio-library/music-library/Api.Artists.md index 94ddad92..5f37a0bb 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Artists.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Artists.md @@ -31,19 +31,68 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists ```json { - "name": "Queen", + "metadata": { + "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": { + "musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c", + "name": "United Kingdom", + "sortName": "United Kingdom", + "disambiguation": null, + "type": "Country", + "iso3166Code": "GB" + }, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, + "genres": [ + { "name": "Rock" } + ], + "tags": [ + { "name": "classic" } + ], + "aliases": [ + { + "name": "Queen", + "sortName": "Queen", + "type": "Artist name", + "locale": "en", + "isPrimary": true, + "beginDate": "1970-06-27", + "endDate": null, + "isEnded": false + } + ] + }, "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "ipis": [], + "isnis": [], "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 + } + ], "albums": [ { "metadata": { "title": "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.", + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -70,14 +119,19 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists { "name": "Rock" }, { "name": "Progressive Rock" } ], - "releaseType": "Album", + "script": "Latn", + "releaseTypes": [ "Album" ], "releaseStatus": "Official", "totalDiscs": 1, - "totalTracks": 12 + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -106,6 +160,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -132,22 +187,35 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists { "name": "Rock" }, { "name": "Progressive Rock" } ], + "isVideo": false, "durationInSeconds": 354, "sampleRate": 44100, "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 980 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [ { "name": "dramatic" }, { "name": "anxious" } @@ -180,6 +248,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "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": null, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, @@ -206,22 +275,35 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists { "name": "Rock" }, { "name": "Pop Rock" } ], + "isVideo": false, "durationInSeconds": 181, "sampleRate": 44100, "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 912 + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "moods": [ { "name": "happy" }, { "name": "warm" } @@ -264,13 +346,63 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists { "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "name": "Queen", + "metadata": { + "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": { + "musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c", + "name": "United Kingdom", + "sortName": "United Kingdom", + "disambiguation": null, + "type": "Country", + "iso3166Code": "GB" + }, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, + "genres": [ + { "name": "Rock" } + ], + "tags": [ + { "name": "classic" } + ], + "aliases": [ + { + "name": "Queen", + "sortName": "Queen", + "type": "Artist name", + "locale": "en", + "isPrimary": true, + "beginDate": "1970-06-27", + "endDate": null, + "isEnded": false + } + ] + }, "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "ipis": [], + "isnis": [], + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, "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 + } + ], "albums": [ { "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", @@ -280,10 +412,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "title": "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.", - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -302,26 +431,27 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "languageName": "English", "nativeName": "English" }, - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], "tags": [ - { - "name": "classic" - }, - { - "name": "vinyl" - } - ] + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -361,27 +491,41 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "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 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, "moods": [ @@ -425,27 +569,41 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "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": null, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "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 + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, "moods": [ @@ -482,9 +640,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists } ] } - ], - "createdOnUtc": "2025-01-01T12:00:00.0000000Z", - "updatedOnUtc": null + ] } ``` @@ -515,13 +671,32 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1& { "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "name": "Queen", + "metadata": { + "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": null, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, + "genres": [], + "tags": [], + "aliases": [] + }, "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", - "contributors": [], - "albums": [], + "ipis": [], + "isnis": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", - "updatedOnUtc": null + "updatedOnUtc": null, + "contributors": [], + "ratings": [], + "albums": [] } ], "currentPage": 1, @@ -586,16 +761,64 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} { "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "name": "Queen", + "metadata": { + "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": { + "musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c", + "name": "United Kingdom", + "sortName": "United Kingdom", + "disambiguation": null, + "type": "Country", + "iso3166Code": "GB" + }, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, + "genres": [ + { "name": "Rock" } + ], + "tags": [ + { "name": "classic" } + ], + "aliases": [ + { + "name": "Queen", + "sortName": "Queen", + "type": "Artist name", + "locale": "en", + "isPrimary": true, + "beginDate": "1970-06-27", + "endDate": null, + "isEnded": false + } + ] + }, "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "ipis": [], + "isnis": [], + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], - "albums": [], - "createdOnUtc": "2025-01-01T12:00:00.0000000Z", - "updatedOnUtc": null + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + } + ], + "albums": [] } ``` @@ -610,13 +833,61 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} ```json { - "name": "Queen", + "metadata": { + "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": { + "musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c", + "name": "United Kingdom", + "sortName": "United Kingdom", + "disambiguation": null, + "type": "Country", + "iso3166Code": "GB" + }, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, + "genres": [ + { "name": "Rock" } + ], + "tags": [ + { "name": "classic" } + ], + "aliases": [ + { + "name": "Queen", + "sortName": "Queen", + "type": "Artist name", + "locale": "en", + "isPrimary": true, + "beginDate": "1970-06-27", + "endDate": null, + "isEnded": false + } + ] + }, "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "ipis": [], + "isnis": [], "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 + } + ], "albums": [ { "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", @@ -624,6 +895,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "title": "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.", + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -650,14 +922,19 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} { "name": "Rock" }, { "name": "Progressive Rock" } ], - "releaseType": "Album", + "script": "Latn", + "releaseTypes": [ "Album" ], "releaseStatus": "Official", "totalDiscs": 1, - "totalTracks": 12 + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -687,6 +964,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -713,22 +991,35 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} { "name": "Rock" }, { "name": "Progressive Rock" } ], + "isVideo": false, "durationInSeconds": 354, "sampleRate": 44100, "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 980 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [ { "name": "dramatic" }, { "name": "anxious" } @@ -762,6 +1053,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "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": null, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, @@ -788,22 +1080,35 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} { "name": "Rock" }, { "name": "Pop Rock" } ], + "isVideo": false, "durationInSeconds": 181, "sampleRate": 44100, "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 912 + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "moods": [ { "name": "happy" }, { "name": "warm" } @@ -846,13 +1151,63 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} { "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "name": "Queen", + "metadata": { + "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": { + "musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c", + "name": "United Kingdom", + "sortName": "United Kingdom", + "disambiguation": null, + "type": "Country", + "iso3166Code": "GB" + }, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, + "genres": [ + { "name": "Rock" } + ], + "tags": [ + { "name": "classic" } + ], + "aliases": [ + { + "name": "Queen", + "sortName": "Queen", + "type": "Artist name", + "locale": "en", + "isPrimary": true, + "beginDate": "1970-06-27", + "endDate": null, + "isEnded": false + } + ] + }, "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "ipis": [], + "isnis": [], + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": "2025-02-01T12:00:00.0000000Z", "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 + } + ], "albums": [ { "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", @@ -862,10 +1217,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "title": "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.", - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -884,26 +1236,27 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "languageName": "English", "nativeName": "English" }, - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], "tags": [ - { - "name": "classic" - }, - { - "name": "vinyl" - } - ] + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -943,27 +1296,41 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "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 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, "moods": [ @@ -1007,27 +1374,41 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} "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": null, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "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 + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, "moods": [ @@ -1064,9 +1445,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} } ] } - ], - "createdOnUtc": "2025-01-01T12:00:00.0000000Z", - "updatedOnUtc": "2025-02-01T12:00:00.0000000Z" + ] } ``` @@ -1082,4 +1461,3 @@ DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} ``` Deletes the artist identified by the route, together with its albums and tracks. - diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index d578a1a1..bdb6e2d9 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -30,12 +30,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "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.", - "durationInSeconds": 354, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 980, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -54,24 +49,43 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "epic" } - ] + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [ { "name": "dramatic" }, { "name": "anxious" } @@ -116,27 +130,41 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "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 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, "moods": [ @@ -204,27 +232,41 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "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 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, "moods": [ @@ -283,12 +325,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "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.", - "durationInSeconds": 354, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 980, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -307,24 +344,43 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "epic" } - ] + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [ { "name": "dramatic" }, { "name": "anxious" } @@ -369,27 +425,41 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "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 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null, "moods": [ diff --git a/docs/technical/api/library/management/Api.Libraries.md b/docs/technical/api/library/management/Api.Libraries.md index 30a6eba7..4963627e 100644 --- a/docs/technical/api/library/management/Api.Libraries.md +++ b/docs/technical/api/library/management/Api.Libraries.md @@ -38,6 +38,9 @@ - [Cancel Library Scan](#cancel-library-scan) - [Cancel Library Scan Request](#cancel-library-scan-request) - [Cancel Library Scan Response](#cancel-library-scan-response) + - [Get Library Path Template Parts](#get-library-path-template-parts) + - [Get Library Path Template Parts Request](#get-library-path-template-parts-request) + - [Get Library Path Template Parts Response](#get-library-path-template-parts-response) ## Library @@ -59,9 +62,10 @@ POST api/v1/libraries "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, - "shouldSkipUnchangedDirectoriesDuringScan": true + "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [] } ``` @@ -83,9 +87,10 @@ POST api/v1/libraries "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null } @@ -118,9 +123,10 @@ GET api/v1/libraries "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null } @@ -154,9 +160,10 @@ GET api/v1/libraries/enabled "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null } @@ -189,9 +196,10 @@ GET api/v1/libraries/{id} "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null } @@ -217,9 +225,10 @@ PUT api/v1/libraries/{id} "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, - "shouldSkipUnchangedDirectoriesDuringScan": true + "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [] } ``` @@ -241,9 +250,10 @@ PUT api/v1/libraries/{id} "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null } @@ -400,3 +410,43 @@ POST api/v1/libraries/{libraryId}/scans/{scanId}/cancel ```js 204 No Content ``` + +### Get Library Path Template Parts + +#### Get Library Path Template Parts Request + +```js +GET api/v1/libraries/path-template-parts/{libraryType} +``` + +#### Get Library Path Template Parts Response + +```js +200 Ok +``` + +```json +{ + "parts": [ + { + "kind": "Artist", + "valueType": "Text", + "defaultRepresentation": "{0}", + "isOptionalByDefault": false + }, + { + "kind": "DiscNumber", + "valueType": "Integer", + "defaultRepresentation": "{0:00}", + "isOptionalByDefault": true + } + ], + "defaultTemplateParts": [ + { + "kind": "Artist", + "representation": "{0}", + "isOptional": false + } + ] +} +``` diff --git a/docs/technical/api/plugins/Api.Plugins.md b/docs/technical/api/plugins/Api.Plugins.md index 79e8bb04..194c76c3 100644 --- a/docs/technical/api/plugins/Api.Plugins.md +++ b/docs/technical/api/plugins/Api.Plugins.md @@ -23,12 +23,22 @@ - [Reorder Library Metadata Providers](#reorder-library-metadata-providers) - [Reorder Library Metadata Providers Request](#reorder-library-metadata-providers-request) - [Reorder Library Metadata Providers Response](#reorder-library-metadata-providers-response) + - [Get Library Artwork Providers](#get-library-artwork-providers) + - [Get Library Artwork Providers Request](#get-library-artwork-providers-request) + - [Get Library Artwork Providers Response](#get-library-artwork-providers-response) + - [Set Library Artwork Provider Enabled](#set-library-artwork-provider-enabled) + - [Set Library Artwork Provider Enabled Request](#set-library-artwork-provider-enabled-request) + - [Set Library Artwork Provider Enabled Response](#set-library-artwork-provider-enabled-response) + - [Reorder Library Artwork Providers](#reorder-library-artwork-providers) + - [Reorder Library Artwork Providers Request](#reorder-library-artwork-providers-request) + - [Reorder Library Artwork Providers Response](#reorder-library-artwork-providers-response) - [Get Library Book Readers](#get-library-book-readers) - [Get Library Book Readers Request](#get-library-book-readers-request) - [Get Library Book Readers Response](#get-library-book-readers-response) - [Set Library Book Reader Enabled](#set-library-book-reader-enabled) - [Set Library Book Reader Enabled Request](#set-library-book-reader-enabled-request) - [Set Library Book Reader Enabled Response](#set-library-book-reader-enabled-response) + - [Music Plugins](#music-plugins) ## Plugins @@ -65,15 +75,20 @@ GET api/v1/plugins ```json [ { - "id": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", - "name": "OpenLibrary", - "author": "Binary Alley", + "id": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", + "name": "MusicBrainz Metadata", + "author": "Lumina", "version": "1.0.0", - "description": "Downloads book metadata from Open Library.", + "description": "Retrieves artist, album and track metadata from MusicBrainz.", "loadStatus": "Loaded", "loadError": null, "settings": { - "language": "en" + "BaseUrl": "https://musicbrainz.org/ws/2/", + "DoesAllowPrivateBaseUrl": "false", + "ContactEmail": "", + "SearchResultLimit": "10", + "ReleaseLookupLimit": "25", + "MinimumRequestIntervalSeconds": "1.0" } } ] @@ -93,28 +108,62 @@ GET api/v1/plugins/{pluginId}/settings 200 Ok ``` +The `type` of a setting descriptor is one of `Text`, `Number`, `Boolean` or `Select`. A `Select` setting also carries the list of `allowedValues` it can take. + ```json { - "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", + "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", "schema": [ { - "key": "language", - "label": "Language", + "key": "BaseUrl", + "label": "Base URL", "type": "Text", - "defaultValue": "en", + "defaultValue": "https://musicbrainz.org/ws/2/", "allowedValues": null }, { - "key": "maxResults", - "label": "Maximum results", + "key": "DoesAllowPrivateBaseUrl", + "label": "Allow LAN/Private Base URL", + "type": "Boolean", + "defaultValue": "false", + "allowedValues": null + }, + { + "key": "ContactEmail", + "label": "Contact Email", + "type": "Text", + "defaultValue": null, + "allowedValues": null + }, + { + "key": "SearchResultLimit", + "label": "Search Result Limit", "type": "Number", "defaultValue": "10", "allowedValues": null + }, + { + "key": "ReleaseLookupLimit", + "label": "Release Lookup Limit", + "type": "Number", + "defaultValue": "25", + "allowedValues": null + }, + { + "key": "MinimumRequestIntervalSeconds", + "label": "Minimum Request Interval (seconds)", + "type": "Number", + "defaultValue": "1.0", + "allowedValues": null } ], "settings": { - "language": "en", - "maxResults": "10" + "BaseUrl": "https://musicbrainz.org/ws/2/", + "DoesAllowPrivateBaseUrl": "false", + "ContactEmail": "", + "SearchResultLimit": "10", + "ReleaseLookupLimit": "25", + "MinimumRequestIntervalSeconds": "1.0" } } ``` @@ -129,10 +178,10 @@ PUT api/v1/plugins/{pluginId}/settings ```json { - "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", + "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", "settings": { - "language": "en", - "maxResults": "25" + "BaseUrl": "https://musicbrainz.org/ws/2/", + "SearchResultLimit": "25" } } ``` @@ -151,6 +200,8 @@ PUT api/v1/plugins/{pluginId}/settings GET api/v1/libraries/{libraryId}/metadata-providers ``` +Returns the metadata providers available for the media library, one entry per plugin that provides metadata, along with whether the provider is enabled for the media library and its rank, which determines the order in which the providers are tried. + #### Get Library Metadata Providers Response ```js @@ -160,8 +211,8 @@ GET api/v1/libraries/{libraryId}/metadata-providers ```json [ { - "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", - "name": "OpenLibrary", + "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", + "name": "MusicBrainz Metadata", "isEnabled": true, "rank": 1 } @@ -179,7 +230,7 @@ PUT api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled ```json { "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", + "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", "isEnabled": true } ``` @@ -202,7 +253,7 @@ PUT api/v1/libraries/{libraryId}/metadata-providers/reorder { "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "pluginIds": [ - "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", + "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d" ] } @@ -214,6 +265,85 @@ PUT api/v1/libraries/{libraryId}/metadata-providers/reorder 200 Ok ``` +### Get Library Artwork Providers + +#### Get Library Artwork Providers Request + +```js +GET api/v1/libraries/{libraryId}/artwork-providers +``` + +Returns the artwork providers available for the media library, one entry per plugin that provides artwork, along with whether the provider is enabled for the media library and its rank, which determines the order in which the providers are tried when resolving the artwork. + +#### Get Library Artwork Providers Response + +```js +200 Ok +``` + +```json +[ + { + "pluginId": "c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42", + "name": "Local Music Artwork", + "isEnabled": true, + "rank": 1 + }, + { + "pluginId": "b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14", + "name": "Cover Art Archive", + "isEnabled": true, + "rank": 2 + } +] +``` + +### Set Library Artwork Provider Enabled + +#### Set Library Artwork Provider Enabled Request + +```js +PUT api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled +``` + +```json +{ + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "pluginId": "b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14", + "isEnabled": true +} +``` + +#### Set Library Artwork Provider Enabled Response + +```js +200 Ok +``` + +### Reorder Library Artwork Providers + +#### Reorder Library Artwork Providers Request + +```js +PUT api/v1/libraries/{libraryId}/artwork-providers/reorder +``` + +```json +{ + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "pluginIds": [ + "c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42", + "b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14" + ] +} +``` + +#### Reorder Library Artwork Providers Response + +```js +200 Ok +``` + ### Get Library Book Readers #### Get Library Book Readers Request @@ -272,3 +402,16 @@ PUT api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled ```js 200 Ok ``` + +## Music Plugins + +The music media library type is served by four plugins, which register their capabilities through `IPluginServiceRegistrator`. A single plugin can expose more than one capability, and the capabilities are enabled and ranked per media library through the endpoints above. + +| Plugin | Capability | Web access | Description | +| --- | --- | --- | --- | +| `MusicBrainz Metadata` | Metadata provider (artist, album, track) | Yes | Retrieves artist, album and track metadata from MusicBrainz. | +| `ID3 Metadata` | Metadata provider (artist, album, track) | No | Populates artist, album and track metadata from the embedded tags of the audio files. | +| `Local Music Artwork` | Artwork provider (artist, album) | No | Reads the artwork of the artists and the albums from the images stored in the folders of a local music library, and can extract the embedded album cover from the audio files. | +| `Cover Art Archive` | Artwork provider (album) | Yes | Retrieves the cover, back, booklet, medium and other artwork of music albums from the Cover Art Archive. | + +The metadata providers are resolved during the metadata enrichment phase of a scan, and the artwork providers during the artwork enrichment phase, in the order given by their rank. diff --git a/docs/technical/architecture/4.1 code-media-library-scanning-diagram.puml b/docs/technical/architecture/4.1 code-media-library-scanning-diagram.puml index 2ba4aedd..e9318281 100644 --- a/docs/technical/architecture/4.1 code-media-library-scanning-diagram.puml +++ b/docs/technical/architecture/4.1 code-media-library-scanning-diagram.puml @@ -39,13 +39,25 @@ end note interface IBooksFileSystemDiscoveryJob { } +interface IMusicFileSystemDiscoveryJob { +} + +interface IMusicMetadataExtractionJob { +} + interface IMediaLibraryScanDiffJob { } interface IMediaLibraryScanHashJob { } -interface IGoodReadsMetadataScrapJob { +interface IMediaLibraryScanProviderConfigurationInvalidationJob { +} + +interface IMediaLibraryScanMetadataEnrichmentJob { +} + +interface IMediaLibraryScanArtworkEnrichmentJob { } interface IMediaLibraryScanResultsSaveJob { @@ -56,6 +68,16 @@ class BooksFileSystemDiscoveryJob { + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task } +class MusicFileSystemDiscoveryJob { + - STAGING_BATCH_SIZE: int = 1000 + + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task +} + +class MusicMetadataExtractionJob { + - EXTRACTION_BATCH_SIZE: int = 1000 + + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task +} + class MediaLibraryScanDiffJob { + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task } @@ -65,8 +87,15 @@ class MediaLibraryScanHashJob { + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task } -class GoodReadsMetadataScrapJob { - - ENRICHMENT_PAGE_SIZE: int = 1000 +class MediaLibraryScanProviderConfigurationInvalidationJob { + + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task +} + +class MediaLibraryScanMetadataEnrichmentJob { + + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task +} + +class MediaLibraryScanArtworkEnrichmentJob { + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task } @@ -94,8 +123,8 @@ end note note right of MediaLibraryScanResultsSaveJob Persists the results of the current scan and swaps the scan - snapshot in a single transaction. Always the last job in the - directed acyclic job graph. + snapshot in a single transaction, then triggers the provider + configuration invalidation job. end note class ScanFailurePublisher { @@ -108,30 +137,6 @@ note top of ScanFailurePublisher releases its processing resources (see ADR-0009). end note -' ============================== HOOKS AND REGISTRY ============================== - -class ScanJobHooks { - + AFTER_FILE_SYSTEM_DISCOVERY: string - + AFTER_SCAN_DIFF: string - + BEFORE_METADATA_ENRICHMENT: string - + AFTER_METADATA_ENRICHMENT: string - + BEFORE_SCAN_RESULTS_SAVE: string -} - -note bottom of ScanJobHooks - Named junction points of the scan job graph where plugin - jobs can be injected (see ADR-0008). -end note - -interface IScanJobRegistry { - + GetJobsForHook(hookName: string, libraryId: LibraryId): IEnumerable -} - -class ScanJobRegistry { - - _jobsByHook: IReadOnlyDictionary> - + GetJobsForHook(hookName: string, libraryId: LibraryId): IEnumerable -} - ' ============================== FACTORIES AND SCANNERS ============================== interface IMediaLibraryScanJobFactory { @@ -151,25 +156,103 @@ class MediaLibraryScannerFactory { } interface IMediaTypeScanner { - + SupportedType: LibraryType - + CreateScanJobsForLibrary(libraryId: LibraryId, downloadMetadataFromWeb: bool): IEnumerable + + SupportedLibraryType: LibraryType + + CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable } interface IBookLibraryTypeScanner { } +interface IMusicLibraryTypeScanner { +} + class BookLibraryTypeScanner { - _mediaScanJobFactory: IMediaLibraryScanJobFactory - - _scanJobRegistry: IScanJobRegistry - + SupportedType: LibraryType - + CreateScanJobsForLibrary(libraryId: LibraryId, downloadMetadataFromWeb: bool): IEnumerable + + SupportedLibraryType: LibraryType + + CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable +} + +class MusicLibraryTypeScanner { + - _mediaScanJobFactory: IMediaLibraryScanJobFactory + + SupportedLibraryType: LibraryType + + CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable +} + +' ============================== MEDIA TYPE STRATEGIES ============================== + +interface IMediaLibraryScanItemMaterializer { + + SupportedLibraryType: LibraryType + + ResetEnrichmentStateForChangedPathsAsync(unitOfWork: IUnitOfWork, libraryId: Guid, paths: IReadOnlyCollection, token: CancellationToken): Task> + + MaterializeItemsAsync(unitOfWork: IUnitOfWork, libraryId: Guid, scanId: Guid, paths: IReadOnlyList, token: CancellationToken): Task> + + ResetMetadataStatusForLibraryAsync(unitOfWork: IUnitOfWork, libraryId: Guid, token: CancellationToken): Task> + + ResetArtworkStatusForLibraryAsync(unitOfWork: IUnitOfWork, libraryId: Guid, token: CancellationToken): Task> +} + +interface IMediaLibraryScanMetadataEnricher { + + SupportedLibraryType: LibraryType + + EnrichAsync(libraryId: LibraryId, scanId: ScanId, userId: UserId, token: CancellationToken): Task +} + +interface IMediaLibraryScanArtworkEnricher { + + SupportedLibraryType: LibraryType + + EnrichAsync(libraryId: LibraryId, scanId: ScanId, userId: UserId, token: CancellationToken): Task +} + +class BooksMediaLibraryScanItemMaterializer { +} + +class MusicMediaLibraryScanItemMaterializer { +} + +class BooksMediaLibraryScanMetadataEnricher { + - ENRICHMENT_PAGE_SIZE: int = 1000 +} + +class MusicMediaLibraryScanMetadataEnricher { + - ENRICHMENT_PAGE_SIZE: int = 200 +} + +class BooksMediaLibraryScanArtworkEnricher { + - ENRICHMENT_PAGE_SIZE: int = 1000 +} + +class MusicMediaLibraryScanArtworkEnricher { + - ENRICHMENT_PAGE_SIZE: int = 200 } note top of BookLibraryTypeScanner Builds the books scan job graph: file system discovery, - scan diff, hashing, optional GoodReads metadata enrichment - and scan results save, splicing the plugin jobs registered - at the ScanJobHooks hook points (see ADR-0008). + scan diff, hashing, scan results save, provider configuration + invalidation, metadata enrichment and artwork enrichment. +end note + +' ============================== PATH TEMPLATE ============================== + +interface ILibraryPathTemplateService { + + GetDefaultTemplate(libraryType: LibraryType): LibraryPathTemplate + + ResolveTemplate(libraryType: LibraryType, providedParts: IReadOnlyList): Result + + Validate(libraryType: LibraryType, template: LibraryPathTemplate): Result + + Parse(libraryType: LibraryType, template: LibraryPathTemplate, relativePath: string, pathSeparator: char): Result> +} + +class LibraryPathTemplateService { +} + +interface ILibraryPathPartCatalog { + + SupportedLibraryType: LibraryType + + GetPartDefinitions(): IReadOnlyList + + GetDefaultTemplate(): LibraryPathTemplate +} + +class MusicLibraryPathPartCatalog { +} + +class BookLibraryPathPartCatalog { +} + +note bottom of ILibraryPathTemplateService + Validates media library path templates and derives item + metadata from paths, using the catalog of each library type. end note ' ============================== SCAN ORCHESTRATION ============================== @@ -179,12 +262,12 @@ class LibraryScan { + LibraryId: LibraryId + UserId: UserId + Status: LibraryScanJobStatus - + {static} Create(libraryId: LibraryId, userId: UserId, pastScans: List): ErrorOr - + QueueScan(): ErrorOr - + StartScan(): ErrorOr - + FinishScan(): ErrorOr - + CancelScan(): ErrorOr - + FailScan(): ErrorOr + + {static} Create(libraryId: LibraryId, userId: UserId, pastScans: List): Result + + QueueScan(): Result + + StartScan(): Result + + FinishScan(): Result + + CancelScan(): Result + + FailScan(): Result } note right of LibraryScan @@ -193,8 +276,8 @@ note right of LibraryScan end note interface IMediaLibraryScanningService { - + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, downloadMetadataFromWeb: bool, token: CancellationToken): Task> - + CancelScan(scan: LibraryScan): ErrorOr + + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, token: CancellationToken): Task> + + CancelScan(scan: LibraryScan): Result } class MediaLibraryScanningService { @@ -202,9 +285,9 @@ class MediaLibraryScanningService { - _mediaLibraryScannerFactory: IMediaLibraryScannerFactory - _mediaLibrariesScanCancellationTracker: IMediaLibrariesScanCancellationTracker - _mediaLibrariesScanProgressTracker: IMediaLibrariesScanProgressTracker - - _publisher: IPublisher - + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, downloadMetadataFromWeb: bool, token: CancellationToken): Task> - + CancelScan(scan: LibraryScan): ErrorOr + - _domainEventPublisher: IDomainEventPublisher + + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, token: CancellationToken): Task> + + CancelScan(scan: LibraryScan): Result } note top of MediaLibraryScanningService @@ -259,11 +342,11 @@ class MediaLibrariesScanCancellationTracker { } interface IMediaLibrariesScanProgressTracker { - + InitializeScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, totalJobs: int): ErrorOr - + UpdateScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId): ErrorOr - + UpdateScanJobProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, progress: MediaLibraryScanJobProgress): ErrorOr - + GetScanProgress(compositeKey: MediaLibraryScanCompositeId): ErrorOr - + RemoveScanProgress(compositeKey: MediaLibraryScanCompositeId): ErrorOr + + InitializeScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, totalJobs: int): Result + + UpdateScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId): Result + + UpdateScanJobProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, progress: MediaLibraryScanJobProgress): Result + + GetScanProgress(compositeKey: MediaLibraryScanCompositeId): Result + + RemoveScanProgress(compositeKey: MediaLibraryScanCompositeId): Result } class MediaLibrariesScanProgressTracker { @@ -285,7 +368,7 @@ class DebouncedMediaLibraryScanProgressNotifier { } class MediaLibraryScanProgressHub { - + SubscribeToScan(scanId: Guid, userId: Guid): Task + + SubscribeToScan(scanId: Guid): Task } note top of MediaLibraryScanProgressHub @@ -296,31 +379,31 @@ end note ' ============================== DOMAIN EVENT HANDLERS ============================== class LibraryScanQueuedDomainEventHandler { - + Handle(domainEvent: LibraryScanQueuedDomainEvent, token: CancellationToken): ValueTask + + HandleAsync(domainEvent: LibraryScanQueuedDomainEvent, token: CancellationToken): ValueTask } class LibraryScanStartedDomainEventHandler { - + Handle(domainEvent: LibraryScanStartedDomainEvent, token: CancellationToken): ValueTask + + HandleAsync(domainEvent: LibraryScanStartedDomainEvent, token: CancellationToken): ValueTask } class LibraryScanFinishedDomainEventHandler { - + Handle(domainEvent: LibraryScanFinishedDomainEvent, token: CancellationToken): ValueTask + + HandleAsync(domainEvent: LibraryScanFinishedDomainEvent, token: CancellationToken): ValueTask } class LibraryScanFailedDomainEventHandler { - + Handle(domainEvent: LibraryScanFailedDomainEvent, token: CancellationToken): ValueTask + + HandleAsync(domainEvent: LibraryScanFailedDomainEvent, token: CancellationToken): ValueTask } class LibraryScanCancelledDomainEventHandler { - + Handle(domainEvent: LibraryScanCancelledDomainEvent, token: CancellationToken): ValueTask + + HandleAsync(domainEvent: LibraryScanCancelledDomainEvent, token: CancellationToken): ValueTask } class LibraryScanProgressChangedDomainEventHandler { - + Handle(domainEvent: LibraryScanProgressChangedDomainEvent, token: CancellationToken): ValueTask + + HandleAsync(domainEvent: LibraryScanProgressChangedDomainEvent, token: CancellationToken): ValueTask } class LibraryScanJobProgressChangedDomainEventHandler { - + Handle(domainEvent: LibraryScanJobProgressChangedDomainEvent, token: CancellationToken): ValueTask + + HandleAsync(domainEvent: LibraryScanJobProgressChangedDomainEvent, token: CancellationToken): ValueTask } ' ============================== JOB MODEL RELATIONSHIPS ============================== @@ -328,30 +411,46 @@ class LibraryScanJobProgressChangedDomainEventHandler { IMediaLibraryScanJob <|.. MediaLibraryScanJob : implements IMediaLibraryScanJob <|-- IBooksFileSystemDiscoveryJob +IMediaLibraryScanJob <|-- IMusicFileSystemDiscoveryJob +IMediaLibraryScanJob <|-- IMusicMetadataExtractionJob IMediaLibraryScanJob <|-- IMediaLibraryScanDiffJob IMediaLibraryScanJob <|-- IMediaLibraryScanHashJob -IMediaLibraryScanJob <|-- IGoodReadsMetadataScrapJob +IMediaLibraryScanJob <|-- IMediaLibraryScanProviderConfigurationInvalidationJob +IMediaLibraryScanJob <|-- IMediaLibraryScanMetadataEnrichmentJob +IMediaLibraryScanJob <|-- IMediaLibraryScanArtworkEnrichmentJob IMediaLibraryScanJob <|-- IMediaLibraryScanResultsSaveJob MediaLibraryScanJob <|-- BooksFileSystemDiscoveryJob : inherits +MediaLibraryScanJob <|-- MusicFileSystemDiscoveryJob : inherits +MediaLibraryScanJob <|-- MusicMetadataExtractionJob : inherits MediaLibraryScanJob <|-- MediaLibraryScanDiffJob : inherits MediaLibraryScanJob <|-- MediaLibraryScanHashJob : inherits -MediaLibraryScanJob <|-- GoodReadsMetadataScrapJob : inherits +MediaLibraryScanJob <|-- MediaLibraryScanProviderConfigurationInvalidationJob : inherits +MediaLibraryScanJob <|-- MediaLibraryScanMetadataEnrichmentJob : inherits +MediaLibraryScanJob <|-- MediaLibraryScanArtworkEnrichmentJob : inherits MediaLibraryScanJob <|-- MediaLibraryScanResultsSaveJob : inherits IBooksFileSystemDiscoveryJob <|.. BooksFileSystemDiscoveryJob : implements +IMusicFileSystemDiscoveryJob <|.. MusicFileSystemDiscoveryJob : implements +IMusicMetadataExtractionJob <|.. MusicMetadataExtractionJob : implements IMediaLibraryScanDiffJob <|.. MediaLibraryScanDiffJob : implements IMediaLibraryScanHashJob <|.. MediaLibraryScanHashJob : implements -IGoodReadsMetadataScrapJob <|.. GoodReadsMetadataScrapJob : implements +IMediaLibraryScanProviderConfigurationInvalidationJob <|.. MediaLibraryScanProviderConfigurationInvalidationJob : implements +IMediaLibraryScanMetadataEnrichmentJob <|.. MediaLibraryScanMetadataEnrichmentJob : implements +IMediaLibraryScanArtworkEnrichmentJob <|.. MediaLibraryScanArtworkEnrichmentJob : implements IMediaLibraryScanResultsSaveJob <|.. MediaLibraryScanResultsSaveJob : implements ' ============================== JOB TRIGGER CHAIN ============================== BooksFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers +MusicFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers MediaLibraryScanDiffJob ..> MediaLibraryScanHashJob : triggers -MediaLibraryScanHashJob ..> GoodReadsMetadataScrapJob : triggers when metadata enrichment is enabled -GoodReadsMetadataScrapJob ..> MediaLibraryScanResultsSaveJob : triggers -MediaLibraryScanHashJob ..> MediaLibraryScanResultsSaveJob : triggers when metadata enrichment is disabled +MediaLibraryScanHashJob ..> MediaLibraryScanResultsSaveJob : triggers +MediaLibraryScanHashJob ..> MusicMetadataExtractionJob : triggers +MusicMetadataExtractionJob ..> MediaLibraryScanResultsSaveJob : triggers +MediaLibraryScanResultsSaveJob ..> MediaLibraryScanProviderConfigurationInvalidationJob : triggers +MediaLibraryScanProviderConfigurationInvalidationJob ..> MediaLibraryScanMetadataEnrichmentJob : triggers +MediaLibraryScanMetadataEnrichmentJob ..> MediaLibraryScanArtworkEnrichmentJob : triggers MediaLibraryScanJob ..> ScanFailurePublisher : publishes failure on unhandled exception @@ -359,21 +458,48 @@ MediaLibraryScanJob ..> ScanFailurePublisher : publishes failure on unhandled ex IMediaLibraryScannerFactory <|.. MediaLibraryScannerFactory : implements IMediaLibraryScanJobFactory <|.. MediaLibraryScanJobFactory : implements -IScanJobRegistry <|.. ScanJobRegistry : implements IMediaTypeScanner <|-- IBookLibraryTypeScanner IBookLibraryTypeScanner <|.. BookLibraryTypeScanner : implements +IMediaTypeScanner <|-- IMusicLibraryTypeScanner +IMusicLibraryTypeScanner <|.. MusicLibraryTypeScanner : implements MediaLibraryScannerFactory ..> IMediaTypeScanner : creates BookLibraryTypeScanner --> IMediaLibraryScanJobFactory : uses -BookLibraryTypeScanner --> IScanJobRegistry : splices plugin jobs BookLibraryTypeScanner ..> IBooksFileSystemDiscoveryJob : creates BookLibraryTypeScanner ..> IMediaLibraryScanDiffJob : creates BookLibraryTypeScanner ..> IMediaLibraryScanHashJob : creates -BookLibraryTypeScanner ..> IGoodReadsMetadataScrapJob : creates BookLibraryTypeScanner ..> IMediaLibraryScanResultsSaveJob : creates +BookLibraryTypeScanner ..> IMediaLibraryScanProviderConfigurationInvalidationJob : creates +BookLibraryTypeScanner ..> IMediaLibraryScanMetadataEnrichmentJob : creates +BookLibraryTypeScanner ..> IMediaLibraryScanArtworkEnrichmentJob : creates +MusicLibraryTypeScanner --> IMediaLibraryScanJobFactory : uses +MusicLibraryTypeScanner ..> IMusicFileSystemDiscoveryJob : creates +MusicLibraryTypeScanner ..> IMediaLibraryScanDiffJob : creates +MusicLibraryTypeScanner ..> IMediaLibraryScanHashJob : creates +MusicLibraryTypeScanner ..> IMusicMetadataExtractionJob : creates +MusicLibraryTypeScanner ..> IMediaLibraryScanResultsSaveJob : creates +MusicLibraryTypeScanner ..> IMediaLibraryScanProviderConfigurationInvalidationJob : creates +MusicLibraryTypeScanner ..> IMediaLibraryScanMetadataEnrichmentJob : creates +MusicLibraryTypeScanner ..> IMediaLibraryScanArtworkEnrichmentJob : creates + +IMediaLibraryScanResultsSaveJob --> IMediaLibraryScanItemMaterializer : delegates to +IMediaLibraryScanProviderConfigurationInvalidationJob --> IMediaLibraryScanItemMaterializer : delegates to +IMediaLibraryScanMetadataEnrichmentJob --> IMediaLibraryScanMetadataEnricher : delegates to +IMediaLibraryScanArtworkEnrichmentJob --> IMediaLibraryScanArtworkEnricher : delegates to +IMediaLibraryScanItemMaterializer <|.. BooksMediaLibraryScanItemMaterializer : implements +IMediaLibraryScanItemMaterializer <|.. MusicMediaLibraryScanItemMaterializer : implements +IMediaLibraryScanMetadataEnricher <|.. BooksMediaLibraryScanMetadataEnricher : implements +IMediaLibraryScanMetadataEnricher <|.. MusicMediaLibraryScanMetadataEnricher : implements +IMediaLibraryScanArtworkEnricher <|.. BooksMediaLibraryScanArtworkEnricher : implements +IMediaLibraryScanArtworkEnricher <|.. MusicMediaLibraryScanArtworkEnricher : implements + +ILibraryPathTemplateService <|.. LibraryPathTemplateService : implements +ILibraryPathPartCatalog <|.. MusicLibraryPathPartCatalog : implements +ILibraryPathPartCatalog <|.. BookLibraryPathPartCatalog : implements +LibraryPathTemplateService --> ILibraryPathPartCatalog : uses +MusicMetadataExtractionJob --> ILibraryPathTemplateService : derives metadata from paths -ScanJobRegistry ..> IMediaLibraryScanJob : resolves plugin jobs for hooks MediaLibraryScanJobFactory ..> IMediaLibraryScanJob : creates ' ============================== SERVICE RELATIONSHIPS ============================== @@ -392,7 +518,7 @@ IMediaLibrariesScanQueue <|.. MediaLibrariesScanQueue : implements MediaLibraryScanJobProcessorJob --> IMediaLibrariesScanQueue : reads from MediaLibraryScanJobProcessorJob --> IMediaLibrariesScanCancellationTracker : links scan token -MediaLibraryScanJobProcessorJob ..> BooksFileSystemDiscoveryJob : triggers root job +MediaLibraryScanJobProcessorJob ..> IMediaLibraryScanJob : triggers root job ' ============================== TRACKER RELATIONSHIPS ============================== diff --git a/docs/technical/architecture/4.1 code-media-library-scanning-diagram.svg b/docs/technical/architecture/4.1 code-media-library-scanning-diagram.svg index 4c09be64..84b81ed4 100644 --- a/docs/technical/architecture/4.1 code-media-library-scanning-diagram.svg +++ b/docs/technical/architecture/4.1 code-media-library-scanning-diagram.svg @@ -1 +1 @@ -Code diagram for Background Services 3.2.1Code diagram for Background Services 3.2.1IMediaLibraryScanJobScanId: ScanIdUserId: UserIdLibraryId: LibraryIdChildren:List<IMediaLibraryScanJob>Parents:List<IMediaLibraryScanJob>Status: LibraryScanJobStatusAddChild(job:IMediaLibraryScanJob)AddParent(job:IMediaLibraryScanJob)ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanJobparentsPayloadsExecuted: intExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskAbstract base class for all medialibrary scan jobs.Jobs form a directed acyclicgraph: every job executes itspayload only once all of its parentshave completed, andthen triggers its children. Each jobcreates its own DIscope throughIServiceScopeFactory (seeADR-0001).IBooksFileSystemDiscoveryJobIMediaLibraryScanDiffJobIMediaLibraryScanHashJobIGoodReadsMetadataScrapJobIMediaLibraryScanResultsSaveJobBooksFileSystemDiscoveryJobSTAGING_BATCH_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanDiffJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanHashJobHASHING_PAGE_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskGoodReadsMetadataScrapJobENRICHMENT_PAGE_SIZE:int = 1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanResultsSaveJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskDiscovers the files of every librarycontent location, writesthem in bounded batches to thestaging results table and, whenthe library opts in, comparesdirectory scan fingerprints toskip unchanged directories (seeADR-0004, ADR-0005,ADR-0007).Marks the staging results againstthe media library scansnapshot of the previous scan witha single database-sidediff (see ADR-0004).Computes the content hashes ofthe files that changed sincethe previous scan, in boundedpages (see ADR-0004).Persists the results of the currentscan and swaps the scansnapshot in a single transaction.Always the last job in thedirected acyclic job graph.ScanFailurePublisherPublishAsync(serviceScopeFactory:IServiceScopeFactory, libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,exception: Exception, token:CancellationToken): TaskHelper used by every scan job topublish theLibraryScanFailedDomainEvent,so that a failed scanreleases its processing resources(see ADR-0009).ScanJobHooksAFTER_FILE_SYSTEM_DISCOVERY:stringAFTER_SCAN_DIFF: stringBEFORE_METADATA_ENRICHMENT:stringAFTER_METADATA_ENRICHMENT:stringBEFORE_SCAN_RESULTS_SAVE:stringNamed junction points of the scanjob graph where pluginjobs can be injected (seeADR-0008).IScanJobRegistryGetJobsForHook(hookName:string, libraryId: LibraryId):IEnumerable<IMediaLibraryScanJob>ScanJobRegistry_jobsByHook:IReadOnlyDictionary<string,IReadOnlyList<Type>>GetJobsForHook(hookName:string, libraryId: LibraryId):IEnumerable<IMediaLibraryScanJob>IMediaLibraryScanJobFactoryCreateJob<TJob>(libraryId:LibraryId): TJobMediaLibraryScanJobFactoryCreateJob<TJob>(libraryId:LibraryId): TJobIMediaLibraryScannerFactoryCreateLibraryScanner(libraryType:LibraryType):IMediaTypeScannerMediaLibraryScannerFactoryCreateLibraryScanner(libraryType:LibraryType):IMediaTypeScannerIMediaTypeScannerSupportedType: LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId,downloadMetadataFromWeb:bool):IEnumerable<IMediaLibraryScanJob>IBookLibraryTypeScannerBookLibraryTypeScanner_mediaScanJobFactory:IMediaLibraryScanJobFactory_scanJobRegistry:IScanJobRegistrySupportedType: LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId,downloadMetadataFromWeb:bool):IEnumerable<IMediaLibraryScanJob>Builds the books scan job graph:file system discovery,scan diff, hashing, optionalGoodReads metadata enrichmentand scan results save, splicing theplugin jobs registeredat the ScanJobHooks hook points(see ADR-0008).LibraryScan_pastScans: List<LibraryScan>LibraryId: LibraryIdUserId: UserIdStatus: LibraryScanJobStatusCreate(libraryId: LibraryId,userId: UserId, pastScans:List<LibraryScan>):ErrorOr<LibraryScan>QueueScan():ErrorOr<Success>StartScan(): ErrorOr<Success>FinishScan():ErrorOr<Success>CancelScan():ErrorOr<Success>FailScan(): ErrorOr<Success>Aggregate root of the library scan,which drives the scanlifecycle through its domainevents.IMediaLibraryScanningServiceStartScanAsync(scan:LibraryScan, libraryType:LibraryType,downloadMetadataFromWeb:bool, token:CancellationToken):Task<ErrorOr<Success>>CancelScan(scan:LibraryScan):ErrorOr<Success>MediaLibraryScanningService_mediaLibrariesScanQueue:IMediaLibrariesScanQueue_mediaLibraryScannerFactory:IMediaLibraryScannerFactory_mediaLibrariesScanCancellationTracker:IMediaLibrariesScanCancellationTracker_mediaLibrariesScanProgressTracker:IMediaLibrariesScanProgressTracker_publisher: IPublisherStartScanAsync(scan:LibraryScan, libraryType:LibraryType,downloadMetadataFromWeb:bool, token:CancellationToken):Task<ErrorOr<Success>>CancelScan(scan:LibraryScan):ErrorOr<Success>Central service that starts a scanby building its job graph,registering it in the cancellationand progress trackers andenqueueing the root jobs, and thatcancels a running scan.IMediaLibrariesScanQueueWriter:ChannelWriter<IMediaLibraryScanJob>Reader:ChannelReader<IMediaLibraryScanJob>MediaLibrariesScanQueue_channel:Channel<IMediaLibraryScanJob>Writer:ChannelWriter<IMediaLibraryScanJob>Reader:ChannelReader<IMediaLibraryScanJob>In-memory queue that receivesonly the root scan jobs of ascan. Children are triggereddirectly by their parents, andare never placed on this queue.MediaLibraryScanJobProcessorJob_mediaScanQueue:IMediaLibrariesScanQueue_mediaLibrariesScanCancellationTracker:IMediaLibrariesScanCancellationTrackerExecuteAsync(token:CancellationToken): TaskBackground service that launchesthe payload execution of theroot scan jobs that arrive on thein-memory queue, firing themin a fire-and-forget manner withoutawaiting their long runningpayload execution (seeADR-0001, ADR-0009).IMediaLibrariesScanCancellationTrackerGetTokenForScan(compositeKey:MediaLibraryScanCompositeId):CancellationTokenRegisterScan(compositeKey:MediaLibraryScanCompositeId)RemoveScan(compositeKey:MediaLibraryScanCompositeId)CancelScan(compositeKey:MediaLibraryScanCompositeId)MediaLibrariesScanCancellationTracker_runningScans:ConcurrentDictionary<MediaLibraryScanCompositeId,CancellationTokenSource>IMediaLibrariesScanProgressTrackerInitializeScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,totalJobs: int):ErrorOr<Created>UpdateScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId):ErrorOr<Updated>UpdateScanJobProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,progress:MediaLibraryScanJobProgress):ErrorOr<Updated>GetScanProgress(compositeKey:MediaLibraryScanCompositeId):ErrorOr<MediaLibraryScanProgress>RemoveScanProgress(compositeKey:MediaLibraryScanCompositeId):ErrorOr<MediaLibraryScanProgress>MediaLibrariesScanProgressTracker_scanProgresses:ConcurrentDictionary<MediaLibraryScanCompositeId,MediaLibraryScanProgress>IMediaLibraryScanProgressNotifierSendLibraryProgressUpdateEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskSendLibraryScanFinishedEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskSendLibraryScanFailedEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskDebouncedMediaLibraryScanProgressNotifier_hubContext:IHubContext<MediaLibraryScanProgressHub>_mediaLibrariesScanProgressTracker:IMediaLibrariesScanProgressTracker_debouncers:ConcurrentDictionary<MediaLibraryScanCompositeId,DebounceDispatcher>MediaLibraryScanProgressHubSubscribeToScan(scanId: Guid,userId: Guid): TaskSignalR hub that groupsconnections per scan, so thatsubscribed clients receivereal-time progress updates.LibraryScanQueuedDomainEventHandlerHandle(domainEvent:LibraryScanQueuedDomainEvent,token: CancellationToken):ValueTaskLibraryScanStartedDomainEventHandlerHandle(domainEvent:LibraryScanStartedDomainEvent,token: CancellationToken):ValueTaskLibraryScanFinishedDomainEventHandlerHandle(domainEvent:LibraryScanFinishedDomainEvent,token: CancellationToken):ValueTaskLibraryScanFailedDomainEventHandlerHandle(domainEvent:LibraryScanFailedDomainEvent,token: CancellationToken):ValueTaskLibraryScanCancelledDomainEventHandlerHandle(domainEvent:LibraryScanCancelledDomainEvent,token: CancellationToken):ValueTaskLibraryScanProgressChangedDomainEventHandlerHandle(domainEvent:LibraryScanProgressChangedDomainEvent,token: CancellationToken):ValueTaskLibraryScanJobProgressChangedDomainEventHandlerHandle(domainEvent:LibraryScanJobProgressChangedDomainEvent,token: CancellationToken):ValueTaskimplementsinheritsinheritsinheritsinheritsinheritsimplementsimplementsimplementsimplementsimplementstriggerstriggerstriggers when metadataenrichment is enabledtriggerstriggers when metadataenrichment is disabledpublishes failure onunhandled exceptionimplementsimplementsimplementsimplementscreatesusessplices plugin jobscreatescreatescreatescreatescreatesresolves plugin jobs forhookscreatesimplementsuseswrites root jobs toregisters scaninitializes progressstarts and cancelsimplementsreads fromlinks scan tokentriggers root jobimplementsimplementsimplementsnotifies SignalR clientsreads progressstarts scancancels scanremoves scanupdates progressnotifies finishremoves scanremoves progressnotifies failureremoves scanremoves progressupdates progressnotifies updateupdates job progressnotifies updateLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Background Services 3.2.1The code diagram for the Background Services 3.2.1 - created with PlantUML \ No newline at end of file +Code diagram for Background Services 3.2.1IMediaLibraryScanJobScanId: ScanIdUserId: UserIdLibraryId: LibraryIdChildren:List<IMediaLibraryScanJob>Parents:List<IMediaLibraryScanJob>Status: LibraryScanJobStatusAddChild(job:IMediaLibraryScanJob)AddParent(job:IMediaLibraryScanJob)ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanJobparentsPayloadsExecuted: intExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskAbstract base class for all medialibrary scan jobs.Jobs form a directed acyclicgraph: every job executes itspayload only once all of its parentshave completed, andthen triggers its children. Each jobcreates its own DIscope throughIServiceScopeFactory (seeADR-0001).IBooksFileSystemDiscoveryJobIMusicFileSystemDiscoveryJobIMusicMetadataExtractionJobIMediaLibraryScanDiffJobIMediaLibraryScanHashJobIMediaLibraryScanProviderConfigurationInvalidationJobIMediaLibraryScanMetadataEnrichmentJobIMediaLibraryScanArtworkEnrichmentJobIMediaLibraryScanResultsSaveJobBooksFileSystemDiscoveryJobSTAGING_BATCH_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMusicFileSystemDiscoveryJobSTAGING_BATCH_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMusicMetadataExtractionJobEXTRACTION_BATCH_SIZE:int = 1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanDiffJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanHashJobHASHING_PAGE_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanProviderConfigurationInvalidationJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanMetadataEnrichmentJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanArtworkEnrichmentJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanResultsSaveJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskDiscovers the files of every librarycontent location, writesthem in bounded batches to thestaging results table and, whenthe library opts in, comparesdirectory scan fingerprints toskip unchanged directories (seeADR-0004, ADR-0005,ADR-0007).Marks the staging results againstthe media library scansnapshot of the previous scan witha single database-sidediff (see ADR-0004).Computes the content hashes ofthe files that changed sincethe previous scan, in boundedpages (see ADR-0004).Persists the results of the currentscan and swaps the scansnapshot in a single transaction,then triggers the providerconfiguration invalidation job.ScanFailurePublisherPublishAsync(serviceScopeFactory:IServiceScopeFactory, libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,exception: Exception, token:CancellationToken): TaskHelper used by every scan job topublish theLibraryScanFailedDomainEvent,so that a failed scanreleases its processing resources(see ADR-0009).IMediaLibraryScanJobFactoryCreateJob<TJob>(libraryId:LibraryId): TJobMediaLibraryScanJobFactoryCreateJob<TJob>(libraryId:LibraryId): TJobIMediaLibraryScannerFactoryCreateLibraryScanner(libraryType:LibraryType):IMediaTypeScannerMediaLibraryScannerFactoryCreateLibraryScanner(libraryType:LibraryType):IMediaTypeScannerIMediaTypeScannerSupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IEnumerable<IMediaLibraryScanJob>IBookLibraryTypeScannerIMusicLibraryTypeScannerBookLibraryTypeScanner_mediaScanJobFactory:IMediaLibraryScanJobFactorySupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IEnumerable<IMediaLibraryScanJob>MusicLibraryTypeScanner_mediaScanJobFactory:IMediaLibraryScanJobFactorySupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IEnumerable<IMediaLibraryScanJob>IMediaLibraryScanItemMaterializerSupportedLibraryType:LibraryTypeResetEnrichmentStateForChangedPathsAsync(unitOfWork:IUnitOfWork, libraryId: Guid,paths:IReadOnlyCollection<string>,token: CancellationToken):Task<Result<Updated>>MaterializeItemsAsync(unitOfWork:IUnitOfWork, libraryId: Guid,scanId: Guid, paths:IReadOnlyList<string>, token:CancellationToken):Task<Result<Success>>ResetMetadataStatusForLibraryAsync(unitOfWork:IUnitOfWork, libraryId: Guid,token: CancellationToken):Task<Result<Updated>>ResetArtworkStatusForLibraryAsync(unitOfWork:IUnitOfWork, libraryId: Guid,token: CancellationToken):Task<Result<Updated>>IMediaLibraryScanMetadataEnricherSupportedLibraryType:LibraryTypeEnrichAsync(libraryId: LibraryId,scanId: ScanId, userId: UserId,token: CancellationToken):TaskIMediaLibraryScanArtworkEnricherSupportedLibraryType:LibraryTypeEnrichAsync(libraryId: LibraryId,scanId: ScanId, userId: UserId,token: CancellationToken):TaskBooksMediaLibraryScanItemMaterializerMusicMediaLibraryScanItemMaterializerBooksMediaLibraryScanMetadataEnricherENRICHMENT_PAGE_SIZE:int = 1000MusicMediaLibraryScanMetadataEnricherENRICHMENT_PAGE_SIZE:int = 200BooksMediaLibraryScanArtworkEnricherENRICHMENT_PAGE_SIZE:int = 1000MusicMediaLibraryScanArtworkEnricherENRICHMENT_PAGE_SIZE:int = 200Builds the books scan job graph:file system discovery,scan diff, hashing, scan resultssave, provider configurationinvalidation, metadata enrichmentand artwork enrichment.ILibraryPathTemplateServiceGetDefaultTemplate(libraryType:LibraryType):LibraryPathTemplateResolveTemplate(libraryType:LibraryType, providedParts:IReadOnlyList<LibraryPathPart>):Result<LibraryPathTemplate>Validate(libraryType:LibraryType, template:LibraryPathTemplate):Result<Success>Parse(libraryType: LibraryType,template: LibraryPathTemplate,relativePath: string,pathSeparator: char):Result<Optional<ParsedLibraryPath>>LibraryPathTemplateServiceILibraryPathPartCatalogSupportedLibraryType:LibraryTypeGetPartDefinitions():IReadOnlyList<LibraryPathPartDefinition>GetDefaultTemplate():LibraryPathTemplateMusicLibraryPathPartCatalogBookLibraryPathPartCatalogValidates media library pathtemplates and derives itemmetadata from paths, using thecatalog of each library type.LibraryScan_pastScans: List<LibraryScan>LibraryId: LibraryIdUserId: UserIdStatus: LibraryScanJobStatusCreate(libraryId: LibraryId,userId: UserId, pastScans:List<LibraryScan>):Result<LibraryScan>QueueScan(): Result<Success>StartScan(): Result<Success>FinishScan(): Result<Success>CancelScan():Result<Success>FailScan(): Result<Success>Aggregate root of the library scan,which drives the scanlifecycle through its domainevents.IMediaLibraryScanningServiceStartScanAsync(scan:LibraryScan, libraryType:LibraryType, token:CancellationToken):Task<Result<Success>>CancelScan(scan:LibraryScan): Result<Success>MediaLibraryScanningService_mediaLibrariesScanQueue:IMediaLibrariesScanQueue_mediaLibraryScannerFactory:IMediaLibraryScannerFactory_mediaLibrariesScanCancellationTracker:IMediaLibrariesScanCancellationTracker_mediaLibrariesScanProgressTracker:IMediaLibrariesScanProgressTracker_domainEventPublisher:IDomainEventPublisherStartScanAsync(scan:LibraryScan, libraryType:LibraryType, token:CancellationToken):Task<Result<Success>>CancelScan(scan:LibraryScan): Result<Success>Central service that starts a scanby building its job graph,registering it in the cancellationand progress trackers andenqueueing the root jobs, and thatcancels a running scan.IMediaLibrariesScanQueueWriter:ChannelWriter<IMediaLibraryScanJob>Reader:ChannelReader<IMediaLibraryScanJob>MediaLibrariesScanQueue_channel:Channel<IMediaLibraryScanJob>Writer:ChannelWriter<IMediaLibraryScanJob>Reader:ChannelReader<IMediaLibraryScanJob>In-memory queue that receivesonly the root scan jobs of ascan. Children are triggereddirectly by their parents, andare never placed on this queue.MediaLibraryScanJobProcessorJob_mediaScanQueue:IMediaLibrariesScanQueue_mediaLibrariesScanCancellationTracker:IMediaLibrariesScanCancellationTrackerExecuteAsync(token:CancellationToken): TaskBackground service that launchesthe payload execution of theroot scan jobs that arrive on thein-memory queue, firing themin a fire-and-forget manner withoutawaiting their long runningpayload execution (seeADR-0001, ADR-0009).IMediaLibrariesScanCancellationTrackerGetTokenForScan(compositeKey:MediaLibraryScanCompositeId):CancellationTokenRegisterScan(compositeKey:MediaLibraryScanCompositeId)RemoveScan(compositeKey:MediaLibraryScanCompositeId)CancelScan(compositeKey:MediaLibraryScanCompositeId)MediaLibrariesScanCancellationTracker_runningScans:ConcurrentDictionary<MediaLibraryScanCompositeId,CancellationTokenSource>IMediaLibrariesScanProgressTrackerInitializeScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,totalJobs: int): Result<Created>UpdateScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId):Result<Updated>UpdateScanJobProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,progress:MediaLibraryScanJobProgress):Result<Updated>GetScanProgress(compositeKey:MediaLibraryScanCompositeId):Result<MediaLibraryScanProgress>RemoveScanProgress(compositeKey:MediaLibraryScanCompositeId):Result<MediaLibraryScanProgress>MediaLibrariesScanProgressTracker_scanProgresses:ConcurrentDictionary<MediaLibraryScanCompositeId,MediaLibraryScanProgress>IMediaLibraryScanProgressNotifierSendLibraryProgressUpdateEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskSendLibraryScanFinishedEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskSendLibraryScanFailedEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskDebouncedMediaLibraryScanProgressNotifier_hubContext:IHubContext<MediaLibraryScanProgressHub>_mediaLibrariesScanProgressTracker:IMediaLibrariesScanProgressTracker_debouncers:ConcurrentDictionary<MediaLibraryScanCompositeId,DebounceDispatcher>MediaLibraryScanProgressHubSubscribeToScan(scanId:Guid): TaskSignalR hub that groupsconnections per scan, so thatsubscribed clients receivereal-time progress updates.LibraryScanQueuedDomainEventHandlerHandleAsync(domainEvent:LibraryScanQueuedDomainEvent,token: CancellationToken):ValueTaskLibraryScanStartedDomainEventHandlerHandleAsync(domainEvent:LibraryScanStartedDomainEvent,token: CancellationToken):ValueTaskLibraryScanFinishedDomainEventHandlerHandleAsync(domainEvent:LibraryScanFinishedDomainEvent,token: CancellationToken):ValueTaskLibraryScanFailedDomainEventHandlerHandleAsync(domainEvent:LibraryScanFailedDomainEvent,token: CancellationToken):ValueTaskLibraryScanCancelledDomainEventHandlerHandleAsync(domainEvent:LibraryScanCancelledDomainEvent,token: CancellationToken):ValueTaskLibraryScanProgressChangedDomainEventHandlerHandleAsync(domainEvent:LibraryScanProgressChangedDomainEvent,token: CancellationToken):ValueTaskLibraryScanJobProgressChangedDomainEventHandlerHandleAsync(domainEvent:LibraryScanJobProgressChangedDomainEvent,token: CancellationToken):ValueTaskimplementsinheritsinheritsinheritsinheritsinheritsinheritsinheritsinheritsinheritsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementstriggerstriggerstriggerstriggerstriggerstriggerstriggerstriggerstriggerspublishes failure on unhandledexceptionimplementsimplementsimplementsimplementscreatesusescreatescreatescreatescreatescreatescreatescreatesusescreatescreatescreatescreatescreatescreatescreatescreatesdelegates todelegates todelegates todelegates toimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsusesderives metadata from pathscreatesimplementsuseswrites root jobs toregisters scaninitializes progressstarts and cancelsimplementsreads fromlinks scan tokentriggers root jobimplementsimplementsimplementsnotifies SignalR clientsreads progressstarts scancancels scanremoves scanupdates progressnotifies finishremoves scanremoves progressnotifies failureremoves scanremoves progressupdates progressnotifies updateupdates job progressnotifies updateLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Background Services 3.2.1The code diagram for the Background Services 3.2.1 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md index d4f5ea08..6f4fa111 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md @@ -36,6 +36,10 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD } } ``` +## Amendments + +- **2026-10-09**: The generic `FileSystemDiscoveryJob` / `IFileSystemDiscoveryJob` was split into per-type discovery jobs (`BooksFileSystemDiscoveryJob`, `MusicFileSystemDiscoveryJob`), and the job execution contract is now `ExecuteAsync(Guid id, TInput input, CancellationToken token)` on `IMediaLibraryScanJob`. The `IServiceScopeFactory` decision itself is unchanged. + ## Consequences ### Positive Outcomes diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md index 51e0a773..1bfd69b4 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md @@ -26,7 +26,11 @@ private static List GetFiles(...) ``` -## Consequences +## Amendments + +- **2026-10-09**: The single generic `FileSystemDiscoveryJob` was split into per-type discovery jobs (`BooksFileSystemDiscoveryJob`, `MusicFileSystemDiscoveryJob`). The `System.IO` guidance of this ADR applies to the books discovery job, which still traverses the file system directly. The music discovery job uses the domain file system provider services (`IFileProviderService`, `IDirectoryProviderService`) instead. + +## Consequences ### Performance vs Purity Tradeoff | Metric | Before (Domain) | After (System.IO) | Delta | diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0005.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0005.md index 02660dca..9458cce2 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0005.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0005.md @@ -4,13 +4,13 @@ **Accepted** (2026-08-08) ## Context -The media library scan pipeline stages the file system items discovered during a scan before comparing them against the `LibraryScanSnapshots` table (ADR-0004). A staging store is needed that: +The media library scan pipeline stages the file system items discovered during a scan before comparing them against the `LibraryScanSnapshots` table ([ADR-0004](architecture-decision-record-0004.md)). A staging store is needed that: 1. receives the discovered file system items in bounded batches, 2. is read by the diff, hash and metadata enrichment jobs, -3. is written by the discovery job and read by later jobs, which run in separate dependency injection scopes (see ADR-0001), hence on separate database connections. +3. is written by the discovery job and read by later jobs, which run in separate dependency injection scopes (see [ADR-0001](architecture-decision-record-0001.md)), hence on separate database connections. -A real SQLite `TEMP` table was considered, but SQLite `TEMP` tables are scoped to a single database connection. Because each media library scan job creates its own `AsyncServiceScope`, and therefore its own `LuminaDbContext` and connection (ADR-0001), a `TEMP` table created by the discovery job would be invisible to the diff job, which runs on a different connection. Making a `TEMP` table work would require pinning a single dedicated connection for the whole staging phase of a scan, a larger architectural carve-out. +A real SQLite `TEMP` table was considered, but SQLite `TEMP` tables are scoped to a single database connection. Because each media library scan job creates its own `AsyncServiceScope`, and therefore its own `LuminaDbContext` and connection ([ADR-0001](architecture-decision-record-0001.md)), a `TEMP` table created by the discovery job would be invisible to the diff job, which runs on a different connection. Making a `TEMP` table work would require pinning a single dedicated connection for the whole staging phase of a scan, a larger architectural carve-out. ## Decision Use a permanent table, `LibraryScanStagingResults`, keyed by `(LibraryScanId, Path)`. Its rows are deleted at the end of the scan (as part of the snapshot swap transaction of the save job) and on scan failure or cancellation. Leftover rows of a crashed scan are inert, because every scan has a unique id, and can be purged by the audit cleanup job. @@ -35,9 +35,9 @@ Use a permanent table, `LibraryScanStagingResults`, keyed by `(LibraryScanId, Pa ### 1. SQLite `TEMP` table with a single pinned connection The whole staging phase would hold one dedicated connection open, and all jobs would share it. -**Rejected**: It conflicts with the per-job scope model of ADR-0001, holds a database connection open for the entire scan duration, and makes the pipeline harder to compose and test. +**Rejected**: It conflicts with the per-job scope model of [ADR-0001](architecture-decision-record-0001.md), holds a database connection open for the entire scan duration, and makes the pipeline harder to compose and test. ### 2. In-memory staging (list of discovered items passed between jobs) The discovery job would pass the full list of discovered items to the diff job. -**Rejected**: It brings back the unbounded memory problem that ADR-0004 eliminates. The staging table is what allows bounded, batched writes. +**Rejected**: It brings back the unbounded memory problem that [ADR-0004](architecture-decision-record-0004.md) eliminates. The staging table is what allows bounded, batched writes. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0008.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0008.md index 6366db95..37c87324 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0008.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0008.md @@ -1,7 +1,7 @@ # Architecture Decision Record (ADR): 0008 - Plugin Hook Points and the Media Library Scan Job Graph ## Status -**Accepted** (2026-08-08) +**Superseded by [ADR-0015](architecture-decision-record-0015.md)** (2026-10-09) ## Context The media library scanning subsystem is meant to be modular: generic jobs, like the scan diff, hashing and results save jobs, are shared by all media library types, while media-type specific jobs, like the GoodReads metadata scrap job for books or a TMDB cover art job for movies, are decoupled and composed into a directed acyclic graph. @@ -15,24 +15,30 @@ Define named hook points for the scan job graph in `ScanJobHooks`: `AfterFileSys Define the `IScanJobRegistry` interface, which maps a hook name to the plugin jobs registered at that hook. The media type scanners (for example `BookLibraryTypeScanner`) splice the plugin jobs returned by the registry into the graph at the corresponding hook points, preserving the parent-child relationships. The composition root of the plugin system provides the registry with the plugin job types; the default registry registers no plugin jobs. -The payload passing between jobs keeps the generic `ExecuteAsync` contract. The core scan jobs are database-centric and ignore the payload, because they exchange the scan state through the staging and snapshot tables (ADR-0004, ADR-0005). Payload passing remains available for plugin jobs that need to exchange data in memory, and the runtime type switching that was used in the previous `HashComparerJob` is eliminated. +The payload passing between jobs keeps the generic `ExecuteAsync` contract. The core scan jobs are database-centric and ignore the payload, because they exchange the scan state through the staging and snapshot tables ([ADR-0004](architecture-decision-record-0004.md), [ADR-0005](architecture-decision-record-0005.md)). Payload passing remains available for plugin jobs that need to exchange data in memory, and the runtime type switching that was used in the previous `HashComparerJob` is eliminated. + +## Amendments + +- **2026-10-09**: Superseded by [ADR-0015](architecture-decision-record-0015.md). The `ScanJobHooks` hook points and the `IScanJobRegistry` / `ScanJobRegistry` were removed, and plugins now contribute capability providers (`IMetadataProvider`, `IArtworkProvider`, `IBookReader`) instead of scan jobs. This ADR is marked superseded rather than amended because its decision is replaced in full by [ADR-0015](architecture-decision-record-0015.md); [ADR-0001](architecture-decision-record-0001.md), [ADR-0003](architecture-decision-record-0003.md) and [ADR-0010](architecture-decision-record-0010.md) stay accepted because only part of their decisions changed. ## Consequences +> The rows struck through reflect the superseded hook point and scan job registry model. They no longer hold, see [ADR-0015](architecture-decision-record-0015.md). + ### Positive Outcomes | Aspect | Benefit | |-----------------------|-----------------------------------------------------------| | Modularity | Media-type specific jobs are composed per scanner | -| Extensibility | Plugins inject jobs at documented hook points | +| ~~Extensibility~~ | ~~Plugins inject jobs at documented hook points~~ (removed, see [ADR-0015](architecture-decision-record-0015.md)) | | Multi-parent support | The base job model keeps full parent-child capabilities | -| Fail fast composition | Wrong payload wiring produces loud errors instead of silent no-ops | +| ~~Fail fast composition~~ | ~~Wrong payload wiring produces loud errors instead of silent no-ops~~ (removed, see [ADR-0015](architecture-decision-record-0015.md)) | ### Risks and Tradeoffs | Risk | Mitigation Strategy | |-------------------------------|-------------------------------------------------------------------| -| Plugin job conflicts | Hook points are named and documented, the composition is validated when the graph is built | +| ~~Plugin job conflicts~~ | ~~Hook points are named and documented, the composition is validated when the graph is built~~ (removed, see [ADR-0015](architecture-decision-record-0015.md)) | | Payload contract misuse | Jobs that expect a payload fail loudly when the edge type does not match | -| Scope creep | Only the sensible hook points are defined, arbitrary injection is not supported | +| ~~Scope creep~~ | ~~Only the sensible hook points are defined, arbitrary injection is not supported~~ (removed, see [ADR-0015](architecture-decision-record-0015.md)) | ## Alternatives Considered diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0009.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0009.md index dc2bc99b..ff4d566c 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0009.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0009.md @@ -4,7 +4,7 @@ **Accepted** (2026-08-08) ## Context -Media library scan jobs are launched in a fire-and-forget manner from the background job processor (`MediaLibraryScanJobProcessorJob`), because only the root jobs are placed on the in-memory queue, and they trigger their children recursively (see ADR-0001 and ADR-0008). The launch mechanism uses `FireAndForgetSafeAsync`, which observes the launched task but does not crash the queue consumer. +Media library scan jobs are launched in a fire-and-forget manner from the background job processor (`MediaLibraryScanJobProcessorJob`), because only the root jobs are placed on the in-memory queue, and they trigger their children recursively (see [ADR-0001](architecture-decision-record-0001.md) and [ADR-0008](architecture-decision-record-0008.md)). The launch mechanism uses `FireAndForgetSafeAsync`, which observes the launched task but does not crash the queue consumer. The scan jobs must report their failures through the existing eventual consistency mechanism, the `LibraryScanFailedDomainEvent`, whose handler marks the scan as failed, releases the scan processing resources and notifies the clients. The previous job implementations only published the failure event on a few specific error paths, so any other exception was silently swallowed, leaving the scan stuck in the `Running` state, leaking its cancellation source and progress entry. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md index ac4ef46c..09680ffa 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md @@ -4,20 +4,28 @@ **Accepted** (2026-08-09) ## Context -ADR-0009 established that every media library scan job wraps its execution in a catch-all that marks the job as `Failed` and publishes the `LibraryScanFailedDomainEvent`. That decision applies to the mandatory scan jobs: file system discovery, scan diff, content hashing and scan results save. These jobs are transactional in nature, and a failure in any of them means the file state of the library was not committed. +[ADR-0009](architecture-decision-record-0009.md) established that every media library scan job wraps its execution in a catch-all that marks the job as `Failed` and publishes the `LibraryScanFailedDomainEvent`. That decision applies to the mandatory scan jobs: file system discovery, scan diff, content hashing and scan results save. These jobs are transactional in nature, and a failure in any of them means the file state of the library was not committed. The metadata enrichment phase runs after the scan results save job, once the file state of the library is committed and the books are materialized. The enrichment phase is best-effort: a book whose metadata could not be retrieved is still browsable with its shell metadata (path and filename-derived title), and a crash mid-enrichment must not roll back the already committed scan results, nor hide the successfully enriched books. This was an explicit product decision: partial enrichment survives a crash, and the scan is not considered failed because a remote metadata provider was unreachable or a provider crashed. ## Decision -The metadata enrichment job (`MediaLibraryScanMetadataEnrichmentJob`) is a best-effort job with failure semantics that differ from the mandatory jobs of ADR-0009: +The metadata enrichment job (`MediaLibraryScanMetadataEnrichmentJob`) is a best-effort job with failure semantics that differ from the mandatory jobs of [ADR-0009](architecture-decision-record-0009.md): - Per-book failures are isolated: a metadata provider that throws, returns unusable metadata, or fails to be applied marks the book as `Failed` (`MetadataStatus.Failed`) and moves to the next book. The other providers are still tried for the same book, and the other books are still processed. - Per-provider failures are isolated: a crashing metadata provider does not prevent the other providers from being tried, in their configured order. - The scan is considered completed (`LibraryScanFinishedDomainEvent`) after the enrichment phase, even when some books failed to be enriched. The failure is recorded on the books, not on the scan. -- Only a host-side catastrophic failure of the enrichment job itself (e.g., a storage error) fails the scan, through the existing catch-all of ADR-0009. In that case the file state is already committed, and a re-scan retries the enrichment. +- Only a host-side catastrophic failure of the enrichment job itself (e.g., a storage error) fails the scan, through the existing catch-all of [ADR-0009](architecture-decision-record-0009.md). In that case the file state is already committed, and a re-scan retries the enrichment. The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`. The event is published by the last job of the directed acyclic job graph: the save job when the library does not permit downloading data from the web (no enrichment phase), or the metadata enrichment job otherwise. +## Amendments + +- **2026-10-09**: The enrichment phase is now three sequential jobs, and the last job of the graph is the artwork enrichment job. + - `MediaLibraryScanProviderConfigurationInvalidationJob` invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, and the metadata derived from the paths when the path template changed. + - `MediaLibraryScanMetadataEnrichmentJob` enriches the metadata and links the media contributors. + - `MediaLibraryScanArtworkEnrichmentJob` resolves the artwork and is always the last job, publishing `LibraryScanFinishedDomainEvent` (see `MediaLibraryScanArtworkEnrichmentJob`). +- **2026-10-09**: The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`; it triggers the provider configuration invalidation job. The metadata enrichment semantics described below apply to both the metadata and the artwork enrichment jobs, and across every media library type with enrichers, including music (`MusicMediaLibraryScanMetadataEnricher`, `MusicMediaLibraryScanArtworkEnricher`), not only books. + ## Consequences ### Positive Outcomes @@ -37,7 +45,7 @@ The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDom ## Alternatives Considered ### 1. Fail the scan on any enrichment failure -Keep ADR-0009 semantics for the enrichment job. +Keep [ADR-0009](architecture-decision-record-0009.md) semantics for the enrichment job. **Rejected**: The file state is already committed, and partial enrichment is better than failing a scan that saved the library. Failing the scan would also roll back nothing, while misleading the user about the scan outcome. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md index 68f31844..4e57fd2f 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md @@ -12,7 +12,7 @@ Key constraints that shaped this decision: 1. **Licensing Change**: MediatR became a commercial product for .NET 8+ projects, requiring a paid license for continued use in production systems. -2. **Narrow Usage Scope**: MediatR is used for command and query dispatching, with a single pipeline behavior (automatic application validation) and no stream requests. Its notification publishing is used for domain event publishing, which is outside the scope of this ADR and is replaced separately (see ADR-0013). +2. **Narrow Usage Scope**: MediatR is used for command and query dispatching, with a single pipeline behavior (automatic application validation) and no stream requests. Its notification publishing is used for domain event publishing, which is outside the scope of this ADR and is replaced separately (see [ADR-0013](architecture-decision-record-0013.md)). 3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, the command and query dispatching provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md index 74e21de2..213b5665 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md @@ -14,7 +14,7 @@ Domain event publishing, the mechanism that fires the `IDomainEvent` objects rai 3. **Publishing sites**: Mediator's `IPublisher` is used from `EventualConsistencyMiddleware` (queued events, published after the transaction commits), from `MediaLibraryScanningService` (scan start events), and from the scan jobs and `ScanFailurePublisher` (progress and failure events). -The remaining publish half carries the same third-party dependency and source-generated registration that ADR-0011 removed from the dispatch half. +The remaining publish half carries the same third-party dependency and source-generated registration that [ADR-0011](architecture-decision-record-0011.md) removed from the dispatch half. ## Decision @@ -38,7 +38,7 @@ The existing assembly scan that registers `ICommandHandler<>`, `IQueryHandler<>` ### Consistency Guarantees Preserved -- Commit-before-publish ordering in `EventualConsistencyMiddleware` is unchanged (see ADR-0002). +- Commit-before-publish ordering in `EventualConsistencyMiddleware` is unchanged (see [ADR-0002](architecture-decision-record-0002.md)). - Re-entrant publishing (a handler publishing another event) is safe: each publish resolves handlers fresh from the scoped provider. - Jobs publish from their own scopes, so handlers receive a fresh unit of work and `DbContext`. @@ -73,4 +73,4 @@ Introduce `IIntegrationEvent` now, with a durable outbox, for inter-bounded-cont Keep the Mediator library for the domain event publishing half. -**Rejected**: for the same reason ADR-0011 rejected it for command and query dispatching - an external dependency, with source-generated registration, for functionality that is fully implementable in-house. +**Rejected**: for the same reason [ADR-0011](architecture-decision-record-0011.md) rejected it for command and query dispatching - an external dependency, with source-generated registration, for functionality that is fully implementable in-house. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0015.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0015.md new file mode 100644 index 00000000..6756845e --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0015.md @@ -0,0 +1,79 @@ +# Architecture Decision Record (ADR): 0015 - Plugin Capability Providers for Media Library Enrichment + +## Status + +**Accepted** (2026-10-09) + +Supersedes [ADR-0008](architecture-decision-record-0008.md). + +## Context + +[ADR-0008](architecture-decision-record-0008.md) extended the media library scanning subsystem with plugin jobs: it defined named scan job hook points in `ScanJobHooks` and a scan job registry (`IScanJobRegistry` / `ScanJobRegistry`) that mapped a hook name to the plugin job types to splice into the scan job graph at that junction. + +That model coupled plugins to the host scan graph. A plugin had to know the internal job model and the junction semantics to contribute anything, the host had to know every plugin job type up front to build the graph, and the resulting graph mixed host jobs and plugin jobs with no clear ownership of the enrichment behavior. It also kept the `HashComparerJob` runtime type switching around, because jobs of different types exchanged differently typed payloads. + +What a plugin actually contributes is data: metadata for a media item, artwork for a media item, or the ability to decode a book. Which jobs run, in what order, and how their results are persisted is a host concern that should not be delegated to plugins. + +## Decision + +Separate plugin capabilities from the host scan graph. Plugins contribute capability providers, and the host owns the graph and decides when to invoke the capabilities. + +### Plugin contracts + +- `IPlugin` carries the identity of the plugin (`Id`, `Name`, `Author`, `Version`, `Description`) and its settings schema (`GetSettingsSchema()`). +- `IPluginServiceRegistrator` registers the services of the plugin into the host dependency injection container through `RegisterServices(IServiceCollection)`. + +### Capability contracts + +The host defines the capability contracts, and a plugin implements the ones it supports: + +| Capability | Contract | Purpose | +|---|---|---| +| Metadata provider | `IMetadataProvider` | Searches for and returns the metadata of a media item (`GetSearchResultsAsync`, `GetMetadataAsync`), declaring its `SupportedLibraryTypes`, the `LookupType` it accepts, and whether it `RequiresWebAccess` | +| Artwork provider | `IArtworkProvider` | Returns the artwork of a media item (`GetArtworkAsync`), declaring its `SupportedLibraryTypes` and whether it `RequiresWebAccess` | +| Book reader | `IBookReader` | Decodes a book format into a normalized reading document (`OpenAsync`, `GetResourceAsync`), declaring its `SupportedExtensions` and `SupportedLibraryTypes` | + +### Registration and selection + +- A plugin registers each capability as a keyed transient service, keyed by its plugin `Id` (for example `AddKeyedTransient(pluginId)`). A single plugin can register several providers, of the same or of different capabilities. +- Plugins contribute zero scan jobs. The scan job graph of each media library type is built entirely by its own scanner from host jobs created through `IMediaLibraryScanJobFactory`. +- The host persists which providers are enabled for each media library and their rank, and exposes that configuration through the media library management endpoints. +- The enrichment jobs resolve the configured, enabled providers of the media library and invoke them in rank order: the metadata enrichment job delegates to `IMediaLibraryScanMetadataEnricher`, the artwork enrichment job delegates to `IMediaLibraryScanArtworkEnricher`, and the results save job delegates to `IMediaLibraryScanItemMaterializer`. + +### Removed + +`ScanJobHooks`, `IScanJobRegistry` and `ScanJobRegistry` are removed, along with the `HashComparerJob` runtime type switching they depended on. [ADR-0008](architecture-decision-record-0008.md) is superseded. + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|---|---| +| Ownership | Plugins contribute data capabilities; the host owns the scan graph and when to invoke them | +| Decoupling | A plugin depends only on the capability contracts, not on the internal job model or the graph junctions | +| Extensibility | A new plugin adds keyed capability services and no host code, and a plugin can expose several capabilities | +| Per-library control | Providers are enabled and ranked per media library, independent of plugin installation | +| Simplicity | No hook registry, no graph splicing across the plugin boundary, and no runtime payload type switching | + +### Risks and Mitigations + +| Risk | Mitigation Strategy | +|---|---| +| A plugin registers a capability a library type does not support | Providers declare `SupportedLibraryTypes`, and the host only offers and invokes providers that support the library being processed | +| Two enabled providers return conflicting metadata | Providers are tried in the configured rank order, so precedence is explicit and user controlled | +| A crashing provider fails the enrichment | Enrichment is best effort and isolates provider failures ([ADR-0010](architecture-decision-record-0010.md)), so one provider cannot fail the scan | + +## Alternatives Considered + +### 1. Keep the scan job hook points and the scan job registry + +**Rejected**: it couples plugins to the host scan graph, forces the host to know plugin job types up front, and mixes host and plugin jobs without a clear owner. It is the model this ADR replaces. + +### 2. Let plugins register scan jobs directly, without a registry + +**Rejected**: it removes the named junction points but keeps the coupling: plugins still have to know the job model, the graph shape and the payload contracts, and the graph still has no single owner. + +### 3. Resolve capability providers by convention, without per-library configuration + +**Rejected**: enabling and ranking providers per media library is a requirement. It lets a user run several metadata or artwork sources for one library, in a chosen precedence, and turn providers off without uninstalling the plugin. diff --git a/docs/technical/domain/Aggregates.AudioLibrary.md b/docs/technical/domain/Aggregates.AudioLibrary.md index 08a4c673..f4df0db0 100644 --- a/docs/technical/domain/Aggregates.AudioLibrary.md +++ b/docs/technical/domain/Aggregates.AudioLibrary.md @@ -1,14 +1,15 @@ - [Lumina Domain](#lumina-domain) - - [Audio Library Aggregate](#audio-library-aggregate) + - [Music Library Aggregate](#music-library-aggregate) - [Artist](#artist) - [Album](#album) - [Track](#track) + - [Audio Rating](#audio-rating) # [Lumina Domain](#lumina-domain) -## [Audio Library Aggregate](#audio-library-aggregate) +## [Music Library Aggregate](#music-library-aggregate) -The audio library aggregate is the aggregate root of the `MusicLibrary` aggregate, which models the music of a media library. An artist is the aggregate root, owning its albums, and each album owns its tracks. Albums and tracks carry full metadata: title, description, release information, languages, genres and tags, and the tracks additionally carry the audio characteristics of their file, their moods and their ISRC codes. The media contributors that make up an artist, or that performed on an album or a track, are carried as `MusicMediaContributor` value objects. +The music library aggregate models the music of a media library. `Artist` is the aggregate root, owning its albums, and each album owns its tracks. Albums and tracks carry full metadata: title, description, release information, languages, genres and tags, and the tracks additionally carry the audio characteristics of their file, their moods and their ISRC codes. The media contributors that make up an artist, or that performed on an album or a track, are carried as `MusicMediaContributor` value objects. ### [Artist](#artist) @@ -18,8 +19,25 @@ class Artist Result Create( LibraryId libraryId, string name, + Optional sortName, + Optional disambiguation, + Optional type, + Optional gender, + Optional country, + Optional area, + Optional beginArea, + Optional endArea, + Optional lifeSpanBegin, + Optional lifeSpanEnd, + bool isEnded, Optional website, Optional musicBrainzArtistId, + List ipis, + List isnis, + List aliases, + List genres, + List tags, + List ratings, List contributors, List albums); } @@ -34,10 +52,58 @@ class Artist "value": "00000000-0000-0000-0000-000000000000" }, "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": { + "musicBrainzAreaId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "name": "United Kingdom", + "sortName": null, + "disambiguation": null, + "type": "Country", + "iso3166Code": "GB" + }, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, "website": "https://www.queenonline.com", "musicBrainzArtistId": { "value": "00000000-0000-0000-0000-000000000000" }, + "ipis": [], + "isnis": [], + "aliases": [ + { + "name": "Queen", + "sortName": "Queen", + "type": "Artist name", + "locale": "en", + "isPrimary": true, + "beginDate": "1970-06-27", + "endDate": null, + "isEnded": false + } + ], + "genres": [ + { "name": "Rock" } + ], + "tags": [ + { "name": "classic" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + } + ], "contributors": [], "albums": [ { @@ -54,9 +120,14 @@ class Album { Result Create( AlbumMetadata metadata, + Optional disambiguation, Optional mediaFormat, + Optional packaging, + Optional script, Optional barcode, - Optional catalogNumber, + List catalogNumbers, + Optional label, + Optional asin, Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, @@ -74,6 +145,7 @@ class Album "metadata": { "title": "A Night at the Opera", "originalTitle": "A Night at the Opera", + "releaseTitle": "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.", "releaseInfo": { "originalReleaseDate": "1975-11-21", @@ -101,16 +173,21 @@ class Album "languageName": "English", "nativeName": "English" }, - "releaseType": "Album", + "releaseTypes": [ "Album" ], "releaseStatus": "Official", "totalDiscs": 1, "totalTracks": 12 }, + "disambiguation": null, "mediaFormat": "CD", + "packaging": "JewelCase", + "script": "Latn", "barcode": { "value": "0042282778329" }, - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": { "value": "00000000-0000-0000-0000-000000000000" }, @@ -149,20 +226,20 @@ class Album class Track { Result Create( - LibraryId libraryId, string path, AudioMetadata metadata, + Optional disambiguation, int trackNumber, Optional discNumber, - List isrcs, + List moods, Optional script, Optional key, Optional bpm, - List moods, - Optional work, + bool isVideo, + List isrcs, + Optional work, Optional musicBrainzRecordingId, Optional musicBrainzTrackId, - Optional musicBrainzWorkId, List contributors, List ratings); } @@ -173,9 +250,6 @@ class Track "id": { "value": "00000000-0000-0000-0000-000000000000" }, - "libraryId": { - "value": "00000000-0000-0000-0000-000000000000" - }, "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", @@ -212,32 +286,50 @@ class Track "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 980 + "bitrate": 980, + "acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f", + "replayGainTrackGain": -7.5, + "replayGainTrackPeak": 0.9877, + "replayGainAlbumGain": -6.8, + "replayGainAlbumPeak": 0.9999 }, + "disambiguation": null, "trackNumber": 1, "discNumber": 1, - "isrcs": [ - { - "value": "GBUM71029604" - } - ], "script": "Latn", "key": "CMajor", "bpm": 72, - "moods": [ - { "name": "dramatic" }, - { "name": "anxious" } - ], - "work": "Bohemian Rhapsody", + "isVideo": false, + "work": { + "musicBrainzWorkId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + } + ], + "iswcs": [] + }, "musicBrainzRecordingId": { "value": "00000000-0000-0000-0000-000000000000" }, "musicBrainzTrackId": { "value": "00000000-0000-0000-0000-000000000000" }, - "musicBrainzWorkId": { - "value": "00000000-0000-0000-0000-000000000000" - }, + "moods": [ + { "name": "dramatic" }, + { "name": "anxious" } + ], + "isrcs": [ + { + "value": "GBUM71029604" + } + ], "contributors": [], "ratings": [ { @@ -249,3 +341,25 @@ class Track ] } ``` + +### [Audio Rating](#audio-rating) + +The rating of a music media element derives from the common `Rating` value object and adds the source the rating came from. + +```csharp +class AudioRating : Rating +{ + Result Create(decimal value, decimal maxValue, Optional source, Optional voteCount); +} +``` + +```json +{ + "value": 9.3, + "maxValue": 10.0, + "source": "MusicBrainz", + "voteCount": 84 +} +``` + +`AudioRatingSource` is `User`, `MusicBrainz`, `Discogs` or `LastFm`. diff --git a/docs/technical/domain/Common.Metadata.md b/docs/technical/domain/Common.Metadata.md index 967e86d9..ff27aef1 100644 --- a/docs/technical/domain/Common.Metadata.md +++ b/docs/technical/domain/Common.Metadata.md @@ -4,6 +4,7 @@ - [Genre](#genre) - [Tag](#tag) - [Rating](#rating) + - [Mood](#mood) - [Release Info](#release-info) - [Language Info](#language-info) @@ -18,7 +19,7 @@ ```csharp class Genre { - ErrorOr Create(string name); + Result Create(string name); } ``` @@ -33,7 +34,7 @@ class Genre ```csharp class Tag { - ErrorOr Create(string name); + Result Create(string name); } ``` @@ -45,19 +46,30 @@ class Tag #### [Rating](#rating) +`Rating` is the abstract base of the ratings of media elements. It carries the numeric value, its maximum and an optional vote count, but no factory of its own, because the concrete ratings of each media type derive from it and add their own source. The rating of the audio library context, `AudioRating` with its `AudioRatingSource`, is documented alongside the music library aggregate. + ```csharp -class Rating +abstract class Rating { - ErrorOr Create(decimal value, decimal maxValue, Optional source = default, Optional voteCount = default); + decimal Value { get; } + decimal MaxValue { get; } + Optional VoteCount { get; } + decimal AsPercentage(); +} +``` + +#### [Mood](#mood) + +```csharp +class Mood +{ + Result Create(string name); } ``` ```json { - "value": 9.3, - "maxValue": 10.0, - "source": "Imdb", - "voteCount": 84 + "name": "dramatic" } ``` @@ -66,8 +78,8 @@ class Rating ```csharp class ReleaseInfo { - ErrorOr Create(Optional originalReleaseDate, Optional originalReleaseYear, - Optional reReleaseDate, Optional reReleaseYear, Optional releaseCountry, Optional releaseVersion); + Result Create(Optional originalReleaseDate, Optional originalReleaseYear, + Optional reReleaseDate, Optional reReleaseYear, Optional releaseCountry, Optional releaseVersion); } ``` @@ -97,4 +109,4 @@ class LanguageInfo "languageName": "French", "nativeName": "Française", } -``` \ No newline at end of file +``` diff --git a/docs/technical/domain/Domain.md b/docs/technical/domain/Domain.md index 1a7f872d..8d3c4be7 100644 --- a/docs/technical/domain/Domain.md +++ b/docs/technical/domain/Domain.md @@ -1,7 +1,23 @@ Domain ├── Audio Library Bounded Context -│      └── Audio Library Aggregate -│              └── Audio Metadata +│      └── Music Library Aggregate +│              ├── Artist Id +│              ├── Album Id +│              ├── Track Id +│              ├── Music Media Contributor +│              ├── Music Brainz Id +│              ├── Music Area +│              ├── Music Artist Alias +│              ├── Music Work +│              ├── Isrc +│              ├── Barcode +│              ├── Album Metadata +│              ├── Audio Metadata +│              ├── Audio Rating +│              ├── Album +│              ├── Track +│              ├── Music Library Type Scanner +│              └── Artist ├── Video Library Bounded Context │      ├── Movie Library Aggregate │      │        ├── Movie Id diff --git a/docs/technical/domain/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md index 4f3d9024..9bae25bd 100644 --- a/docs/technical/domain/UbiquitousLanguage.md +++ b/docs/technical/domain/UbiquitousLanguage.md @@ -28,19 +28,10 @@ - _**Music Video**_: A video representation of a song ## Audio Content -- _**Song**_: An individual music track -- _**Album**_: A collection of songs -- _**Artist**_: The creator of music content -- _**Audiobook**_: A narrated version of a book -- _**Live Recording**_: Audio or video of a live performance -- _**Interview**_: Audio or video recording of a conversation -- _**Cover Song**_: A rendition of a song performed by an artist other than the original -- _**Remix**_: A modified version of an original song -- _**Sound Effect**_: A short audio clip used for specific purposes -- _**Soundtrack**_: A collection of music used in a film or TV show -- _**Podcast**_: A series of audio episodes -- _**Podcast Episode**_: An individual installment of a podcast -- _**Radio Show**_: An audio program broadcast on the radio +- _**Track**_: An individual music track, the smallest unit of music in a music library (the entity is named Track, not Song) +- _**Album**_: A release that gathers the tracks of an artist +- _**Artist**_: The creator of music content, the root of the music library aggregate +- _**MusicReleaseType**_: The set of content types a music release can carry, like Album, Single, Ep, Compilation, AudioBook, Interview, Live, Remix, Soundtrack or SpokenWord ## Written Content - _**Book**_: A standalone written work @@ -79,15 +70,9 @@ - Anime - YouTubeVideo - MusicVideo -- Song +- Track - Album - Artist -- Audiobook -- LiveRecording -- Interview -- CoverSong -- Remix -- SoundEffect - Podcast - PodcastEpisode - Book @@ -118,7 +103,7 @@ ## Aggregates - VideoLibrary (root: VideoLibrary, entities: TVShow, Season, Episode, Movie, FilmSeries, ConcertVideo, Documentary, TutorialVideo, HomeVideo, Anime, YouTubeVideo, MusicVideo) -- AudioLibrary (root: AudioLibrary, entities: Song, Album, Artist, Audiobook, LiveRecording, Interview, CoverSong, Remix, SoundEffect) +- MusicLibrary (root: Artist, entities: Album, Track) - PodcastLibrary (root: PodcastLibrary, entities: Podcast, PodcastEpisode) - WrittenContentLibrary (root: WrittenContentLibrary, entities: Book, EBook, BookSeries, ComicBook, ComicSeries, Magazine, MagazineIssue, Newspaper, Manga, GraphicNovel, AcademicPaper, SheetMusic, Screenplay) - PhotoLibrary (root: PhotoLibrary, entities: Photo, PhotoAlbum, AlbumArtwork, MoviePoster) @@ -175,14 +160,25 @@ - StreamInfo - StreamingQuality - UserPreferences -- Rating +- Rating (abstract) +- AudioRating - Genre +- Mood - ReleaseInfo - LanguageInfo +- AlbumMetadata +- MusicMediaContributor +- MusicBrainzId +- MusicArea +- MusicArtistAlias +- MusicWork +- Isrc +- Barcode ## Domain Services -- MediaScanner (with specialized scanners for each media type) -- MetadataFetcher (with different strategies for various media types and sources) +- Music Library Type Scanner +- Music File System Discovery Job +- Music Metadata Extraction Job - TranscodingService - StreamingService - AudiobookPlaybackService @@ -216,8 +212,8 @@ ## Bounded Contexts - MediaManagement - - Aggregates: VideoLibrary, AudioLibrary, PodcastLibrary, WrittenContentLibrary, PhotoLibrary - - Services: MediaScanner, MetadataFetcher, TranscodingService + - Aggregates: VideoLibrary, MusicLibrary, PodcastLibrary, WrittenContentLibrary, PhotoLibrary + - Services: Music Library Type Scanner, Music File System Discovery Job, Music Metadata Extraction Job - UserExperience - Aggregates: UserProfile - Services: RecommendationEngine, ContentCurationService, UserActivityTrackingService diff --git a/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http b/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http index 1f173f5b..93f7424a 100644 --- a/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http +++ b/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http @@ -7,6 +7,7 @@ Content-Type: application/json "title": "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.", + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -15,10 +16,6 @@ Content-Type: application/json "releaseCountry": "GB", "releaseVersion": "Remastered" }, - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, "language": { "languageCode": "en", "languageName": "English", @@ -29,18 +26,27 @@ Content-Type: application/json "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "vinyl" } - ] + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -69,12 +75,7 @@ Content-Type: application/json "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.", - "durationInSeconds": 354, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 980, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -93,24 +94,50 @@ Content-Type: application/json "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "epic" } - ] + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "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" } @@ -128,13 +155,6 @@ Content-Type: application/json "source": "LastFm", "voteCount": 1234 } - ], - "moods": [ - { "name": "dramatic" }, - { "name": "anxious" } - ], - "isrcs": [ - { "value": "GBUM71029604" } ] }, { @@ -143,12 +163,7 @@ Content-Type: application/json "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.", - "durationInSeconds": 181, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 912, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, @@ -167,24 +182,50 @@ Content-Type: application/json "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "love" } + ], "genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "love" } - ] + "isVideo": false, + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "moods": [ + { "name": "happy" }, + { "name": "warm" } + ], + "isrcs": [ + { "value": "GBUM71029609" } + ], "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } @@ -202,13 +243,6 @@ Content-Type: application/json "source": "LastFm", "voteCount": 567 } - ], - "moods": [ - { "name": "happy" }, - { "name": "warm" } - ], - "isrcs": [ - { "value": "GBUM71029609" } ] } ] diff --git a/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbum.http b/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbum.http index 53a701cd..372ba338 100644 --- a/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbum.http +++ b/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbum.http @@ -7,6 +7,7 @@ Content-Type: application/json "title": "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.", + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -15,10 +16,6 @@ Content-Type: application/json "releaseCountry": "GB", "releaseVersion": "Remastered" }, - "releaseType": "Album", - "releaseStatus": "Official", - "totalDiscs": 1, - "totalTracks": 12, "language": { "languageCode": "en", "languageName": "English", @@ -29,18 +26,27 @@ Content-Type: application/json "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "vinyl" } - ] + "script": "Latn", + "releaseTypes": [ "Album" ], + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", diff --git a/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http b/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http index 56cba33b..e9f22e83 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http @@ -3,19 +3,68 @@ Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "name": "Queen", + "metadata": { + "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": { + "musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c", + "name": "United Kingdom", + "sortName": "United Kingdom", + "disambiguation": null, + "type": "Country", + "iso3166Code": "GB" + }, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, + "genres": [ + { "name": "Rock" } + ], + "tags": [ + { "name": "classic" } + ], + "aliases": [ + { + "name": "Queen", + "sortName": "Queen", + "type": "Artist name", + "locale": "en", + "isPrimary": true, + "beginDate": "1970-06-27", + "endDate": null, + "isEnded": false + } + ] + }, "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "ipis": [], + "isnis": [], "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 + } + ], "albums": [ { "metadata": { "title": "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.", + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -42,14 +91,19 @@ Content-Type: application/json { "name": "Rock" }, { "name": "Progressive Rock" } ], - "releaseType": "Album", + "script": "Latn", + "releaseTypes": [ "Album" ], "releaseStatus": "Official", "totalDiscs": 1, - "totalTracks": 12 + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -78,6 +132,7 @@ Content-Type: application/json "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -104,22 +159,35 @@ Content-Type: application/json { "name": "Rock" }, { "name": "Progressive Rock" } ], + "isVideo": false, "durationInSeconds": 354, "sampleRate": 44100, "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 980 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [ { "name": "dramatic" }, { "name": "anxious" } @@ -152,6 +220,7 @@ Content-Type: application/json "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": null, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, @@ -178,22 +247,35 @@ Content-Type: application/json { "name": "Rock" }, { "name": "Pop Rock" } ], + "isVideo": false, "durationInSeconds": 181, "sampleRate": 44100, "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 912 + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "moods": [ { "name": "happy" }, { "name": "warm" } diff --git a/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtist.http b/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtist.http index 23ddb7ec..37b3b299 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtist.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtist.http @@ -3,13 +3,61 @@ Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "name": "Queen", + "metadata": { + "name": "Queen", + "sortName": "Queen", + "disambiguation": null, + "type": "Group", + "gender": null, + "country": "GB", + "area": { + "musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c", + "name": "United Kingdom", + "sortName": "United Kingdom", + "disambiguation": null, + "type": "Country", + "iso3166Code": "GB" + }, + "beginArea": null, + "endArea": null, + "lifeSpanBegin": "1970-06-27", + "lifeSpanEnd": null, + "isEnded": false, + "genres": [ + { "name": "Rock" } + ], + "tags": [ + { "name": "classic" } + ], + "aliases": [ + { + "name": "Queen", + "sortName": "Queen", + "type": "Artist name", + "locale": "en", + "isPrimary": true, + "beginDate": "1970-06-27", + "endDate": null, + "isEnded": false + } + ] + }, "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "ipis": [], + "isnis": [], "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 + } + ], "albums": [ { "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", @@ -17,6 +65,7 @@ Content-Type: application/json "title": "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.", + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-11-21", "originalReleaseYear": 1975, @@ -43,14 +92,19 @@ Content-Type: application/json { "name": "Rock" }, { "name": "Progressive Rock" } ], - "releaseType": "Album", + "script": "Latn", + "releaseTypes": [ "Album" ], "releaseStatus": "Official", "totalDiscs": 1, - "totalTracks": 12 + "totalTracks": 12, + "releaseTitle": "A Night at the Opera" }, "mediaFormat": "CD", + "packaging": "JewelCase", "barcode": "0042282778329", - "catalogNumber": "EMC 4008", + "catalogNumbers": ["EMC 4008"], + "label": "EMI", + "asin": "B000000000", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", @@ -80,6 +134,7 @@ Content-Type: application/json "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": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -106,22 +161,35 @@ Content-Type: application/json { "name": "Rock" }, { "name": "Progressive Rock" } ], + "isVideo": false, "durationInSeconds": 354, "sampleRate": 44100, "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 980 + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [ { "name": "dramatic" }, { "name": "anxious" } @@ -155,6 +223,7 @@ Content-Type: application/json "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": null, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, @@ -181,22 +250,35 @@ Content-Type: application/json { "name": "Rock" }, { "name": "Pop Rock" } ], + "isVideo": false, "durationInSeconds": 181, "sampleRate": 44100, "channels": 2, "bitDepth": 16, "audioCodec": "FLAC", - "bitrate": 912 + "bitrate": 912, + "acoustId": null, + "replayGainTrackGain": null, + "replayGainTrackPeak": null, + "replayGainAlbumGain": null, + "replayGainAlbumPeak": null }, "trackNumber": 7, "discNumber": 1, "script": "Latn", "key": "BMajor", "bpm": 118, - "work": "You're My Best Friend", + "work": { + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "title": "You're My Best Friend", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", - "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "moods": [ { "name": "happy" }, { "name": "warm" } diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/AddTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/AddTrack.http index 2bbfabe7..28d25334 100644 --- a/docs/technical/requests/library/audio-library/music-library/tracks/AddTrack.http +++ b/docs/technical/requests/library/audio-library/music-library/tracks/AddTrack.http @@ -8,12 +8,7 @@ Content-Type: application/json "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.", - "durationInSeconds": 354, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 980, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -32,24 +27,43 @@ Content-Type: application/json "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "epic" } - ] + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [ { "name": "dramatic" }, { "name": "anxious" } diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http index f7ae653d..e8bd3ec3 100644 --- a/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http +++ b/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http @@ -8,12 +8,7 @@ Content-Type: application/json "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.", - "durationInSeconds": 354, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 980, + "disambiguation": null, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, @@ -32,24 +27,43 @@ Content-Type: application/json "languageName": "English", "nativeName": "English" }, + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], - "tags": [ - { "name": "classic" }, - { "name": "epic" } - ] + "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": "Bohemian Rhapsody", + "work": { + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "title": "Bohemian Rhapsody", + "type": "Song", + "languages": [ + { "languageCode": "en", "languageName": "English", "nativeName": "English" } + ], + "iswcs": [] + }, "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", - "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [ { "name": "dramatic" }, { "name": "anxious" } diff --git a/docs/technical/requests/library/management/AddLibrary.http b/docs/technical/requests/library/management/AddLibrary.http index f6136db5..0a20c31f 100644 --- a/docs/technical/requests/library/management/AddLibrary.http +++ b/docs/technical/requests/library/management/AddLibrary.http @@ -11,7 +11,11 @@ Content-Type: application/json "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, - "shouldSkipUnchangedDirectoriesDuringScan": true + "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [ + { "kind": "Artist", "representation": "{0}", "isOptional": false }, + { "kind": "Separator", "representation": "", "isOptional": false } + ] } diff --git a/docs/technical/requests/library/management/GetLibraryPathTemplateParts.http b/docs/technical/requests/library/management/GetLibraryPathTemplateParts.http new file mode 100644 index 00000000..1562fed7 --- /dev/null +++ b/docs/technical/requests/library/management/GetLibraryPathTemplateParts.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/path-template-parts/Music +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/management/UpdateLibrary.http b/docs/technical/requests/library/management/UpdateLibrary.http index 5cc9136c..aa82d623 100644 --- a/docs/technical/requests/library/management/UpdateLibrary.http +++ b/docs/technical/requests/library/management/UpdateLibrary.http @@ -13,7 +13,11 @@ Content-Type: application/json "coverImage": null, "isEnabled": true, "isLocked": false, - "downloadMetadataFromWeb": true, + "canDownloadMetadataFromWeb": true, "shouldSaveMetadataInMediaDirectories": true, - "shouldSkipUnchangedDirectoriesDuringScan": true + "shouldSkipUnchangedDirectoriesDuringScan": true, + "pathTemplateParts": [ + { "kind": "Artist", "representation": "{0}", "isOptional": false }, + { "kind": "Separator", "representation": "", "isOptional": false } + ] } diff --git a/docs/technical/requests/plugins/UpdatePluginSettings.http b/docs/technical/requests/plugins/UpdatePluginSettings.http index bd63b023..3d788fbd 100644 --- a/docs/technical/requests/plugins/UpdatePluginSettings.http +++ b/docs/technical/requests/plugins/UpdatePluginSettings.http @@ -5,7 +5,7 @@ Content-Type: application/json { "pluginId": "{{$guid}}", "settings": { - "language": "en", - "includeSeries": "true" + "BaseUrl": "https://musicbrainz.org/ws/2/", + "SearchResultLimit": "25" } } diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs index e3ffd5e3..557bf102 100644 --- a/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs +++ b/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs @@ -38,30 +38,30 @@ internal sealed class CalibreArtworkProvider : IArtworkProvider /// The lookup describing the book to get the cover for. /// Cancellation token that can be used to stop the execution. - /// The cover of the book, or when no cover was found. - public Task GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + /// The cover of the book, or an empty collection when no cover was found. + public Task> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(lookup.Path)) - return Task.FromResult(null); + return Task.FromResult>([]); string bookDirectory = Path.GetDirectoryName(lookup.Path) ?? string.Empty; string opfFilePath = Path.Combine(bookDirectory, "metadata.opf"); if (!File.Exists(opfFilePath)) - return Task.FromResult(null); + return Task.FromResult>([]); OpfDocumentDto document = OpfReader.Read(opfFilePath); if (string.IsNullOrWhiteSpace(document.CoverHref)) - return Task.FromResult(null); + return Task.FromResult>([]); // the cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed string coverFileName = Path.GetFileName(document.CoverHref); if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref)) - return Task.FromResult(null); + return Task.FromResult>([]); string coverFilePath = Path.Combine(bookDirectory, coverFileName); if (!File.Exists(coverFilePath)) - return Task.FromResult(null); + return Task.FromResult>([]); - return Task.FromResult(new ArtworkDto(LocalPath: coverFilePath, RemoteUrl: null)); + return Task.FromResult>([new ArtworkDto(ArtworkType.Cover, Ordinal: 0, LocalPath: coverFilePath, RemoteUrl: null)]); } } diff --git a/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs index 092349c5..f8fc8a0c 100644 --- a/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs +++ b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs @@ -1,5 +1,6 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.SecurityTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.IntegrationTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")] diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs new file mode 100644 index 00000000..aa1899b3 --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings; +using Lumina.Plugins.CoverArtArchive.Core; +using Lumina.Plugins.CoverArtArchive.Core.Api; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +using System.Net.Http; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the Cover Art Archive artwork provider into the Dependency Injection container. +/// +internal static class CoverArtArchiveServices +{ + /// + /// Registers the services of the Cover Art Archive artwork provider into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the artwork. + /// Action used to configure the . + /// The updated . + internal static IServiceCollection AddCoverArtArchiveArtworkProvider(this IServiceCollection services, Guid pluginId, Action? settingsCallback = null) + { + ArgumentNullException.ThrowIfNull(services); + + // Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback. + services.TryAddScoped(serviceProvider => + { + CoverArtArchiveSettingsDto defaults = new(); + settingsCallback?.Invoke(defaults); + + IPluginSettingsStore? settingsStore = serviceProvider.GetService(); + return new CoverArtArchiveSettingsProvider(settingsStore, pluginId, defaults); + }); + + // The throttle must be process-wide, because the Cover Art Archive API enforces its request policy across all callers, not per scope. + services.TryAddSingleton(); + + // The response cache is process-wide, so that an entity shared by many items, like the release group shared by the releases of an album, + // is fetched only once during a run. + services.TryAddSingleton(); + + // Automatic redirects are disabled on purpose: the metadata endpoints answer with a temporary redirect to the Internet Archive, and the client + // follows that redirect itself, checking every hop against CoverArtArchiveHosts. Letting the primary handler follow redirects automatically + // would make it follow whatever Location the response carries, which is server controlled, and would bypass that host check, which is the SSRF + // control here; the base URL being a constant does not make the redirect target trustworthy. + services.AddHttpClient() + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); + + // Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations. + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponse.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponse.cs new file mode 100644 index 00000000..3aa98afa --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the artwork of a release or a release group from the Cover Art Archive API. +/// +internal sealed record CoverArtArchiveArtworkResponse +{ + /// + /// Gets the images of the artwork. It is nullable because the deserializer writes a JSON null over the initializer, and may also contain null elements. + /// + [JsonPropertyName("images")] + public List? Images { get; init; } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveImageResponse.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveImageResponse.cs new file mode 100644 index 00000000..4d1a297c --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/Contracts/Responses/CoverArtArchiveImageResponse.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a single image of the artwork of a release or a release group from the Cover Art Archive API. +/// +internal sealed record CoverArtArchiveImageResponse +{ + /// + /// Gets the URL of the full size image. + /// + [JsonPropertyName("image")] + public string? Image { get; init; } + + /// + /// Gets the URL of the thumbnail of the image. + /// + [JsonPropertyName("thumbnail")] + public string? Thumbnail { get; init; } + + /// + /// Gets the types of the image, like "Front", "Back", "Booklet", "Medium", "Tray", "Spine" or "Poster". + /// It is nullable because the deserializer writes a JSON null over the initializer, and may also contain null elements. + /// + [JsonPropertyName("types")] + public List? Types { get; init; } + + /// + /// Gets a value indicating whether the image is the front cover. + /// + [JsonPropertyName("front")] + public bool IsFront { get; init; } + + /// + /// Gets a value indicating whether the image is the back cover. + /// + [JsonPropertyName("back")] + public bool IsBack { get; init; } + + /// + /// Gets the optional comment describing the image. + /// + [JsonPropertyName("comment")] + public string? Comment { get; init; } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/DTO/Settings/CoverArtArchiveSettingsDto.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/DTO/Settings/CoverArtArchiveSettingsDto.cs new file mode 100644 index 00000000..f9d5efe4 --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/Models/DTO/Settings/CoverArtArchiveSettingsDto.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings; + +/// +/// Data transfer object for the settings that configure the Cover Art Archive artwork plugin. +/// +internal sealed class CoverArtArchiveSettingsDto +{ + /// + /// Gets or sets the user agent sent with every request to the Cover Art Archive API. + /// + public string UserAgent { get; set; } = "Lumina-CoverArtArchive/1.0"; + + /// + /// Gets or sets the contact email sent with every request to the Cover Art Archive API. + /// The MetaBrainz services expect a meaningful user agent that carries a way to contact its author. + /// + public string? ContactEmail { get; set; } + + /// + /// Gets or sets the minimum interval between consecutive requests to the Cover Art Archive API, so that the public service is not overwhelmed. + /// + public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0); +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs new file mode 100644 index 00000000..08cde755 --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs @@ -0,0 +1,256 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Core.Api; + +/// +/// HTTP client that calls the Cover Art Archive API and deserializes its JSON responses into typed response models. +/// +internal sealed class CoverArtArchiveHttpClient +{ + private const string BASE_URL = "https://coverartarchive.org/"; + + // Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich. + private const int MAXIMUM_ATTEMPT_COUNT = 3; + + // The metadata endpoints of the Cover Art Archive answer with a temporary redirect to the Internet Archive, so a bounded number of redirects is followed. + private const int MAXIMUM_REDIRECT_COUNT = 3; + + // The delay requested by a rate limited response is honored, but only up to this many seconds, so a misbehaving server cannot stall the scan. + private const double MAXIMUM_RETRY_DELAY_SECONDS = 60; + + private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web); + + private readonly HttpClient _httpClient; + private readonly CoverArtArchiveSettingsProvider _settingsProvider; + private readonly CoverArtArchiveRequestThrottle _requestThrottle; + private readonly CoverArtArchiveResponseCache _responseCache; + + /// + /// Initializes a new instance of the class. + /// + /// The used to send requests to the Cover Art Archive API. + /// The provider of the settings that configure the Cover Art Archive API requests. + /// The process-wide throttle that spaces out the requests sent to the Cover Art Archive API. + /// The process-wide cache that avoids fetching the same entity more than once during a run. + public CoverArtArchiveHttpClient(HttpClient httpClient, CoverArtArchiveSettingsProvider settingsProvider, CoverArtArchiveRequestThrottle requestThrottle, CoverArtArchiveResponseCache responseCache) + { + _httpClient = httpClient; + _settingsProvider = settingsProvider; + _requestThrottle = requestThrottle; + _responseCache = responseCache; + } + + /// + /// Gets the artwork of the release identified by . + /// + /// The MusicBrainz identifier of the release. + /// Cancellation token that can be used to stop the execution. + /// The artwork of the release, or when the release has no artwork. + public Task GetReleaseArtworkAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync($"release/{musicBrainzReleaseId:D}", cancellationToken); + } + + /// + /// Gets the artwork of the release group identified by . + /// + /// The MusicBrainz identifier of the release group. + /// Cancellation token that can be used to stop the execution. + /// The artwork of the release group, or when the release group has no artwork. + public Task GetReleaseGroupArtworkAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync($"release-group/{musicBrainzReleaseGroupId:D}", cancellationToken); + } + + /// + /// Gets the JSON resource at the given relative URL and deserializes it into . + /// + /// The type to deserialize the JSON response into. + /// The URL of the resource, relative to the base address. + /// Cancellation token that can be used to stop the execution. + /// The deserialized resource, or when the resource was not found. + private async Task GetJsonOrNullAsync(string relativeUrl, CancellationToken cancellationToken) + { + // A cached response, including a confirmed absence of artwork, removes the repeated lookups of the same entity, like the release group that the + // releases of an edition heavy library share, or the same library scanned again while the entry is still valid. + if (_responseCache.TryGet(relativeUrl, out string? cachedJson)) + return string.IsNullOrEmpty(cachedJson) ? default : JsonSerializer.Deserialize(cachedJson, s_serializerOptions); + + CoverArtArchiveSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + + using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false); + // A 404 means the entity exists but has no artwork, which is a normal miss rather than an error, so it is reported as no result and cached as such. + if (response.StatusCode == HttpStatusCode.NotFound) + { + _responseCache.Set(relativeUrl, string.Empty); + return default; + } + response.EnsureSuccessStatusCode(); + + string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + TModel? model = JsonSerializer.Deserialize(json, s_serializerOptions); + _responseCache.Set(relativeUrl, json); + return model; + } + + /// + /// Sends a GET request to the Cover Art Archive API, throttled to respect the configured minimum request interval. Transient failures and + /// rate limiting are retried, so a single hiccup does not surface as a failed resolution. + /// + /// The settings that configure the Cover Art Archive API requests. + /// The URL of the resource, relative to the base address. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message for the request. + private async Task SendAsync(CoverArtArchiveSettingsDto settings, string relativeUrl, CancellationToken cancellationToken) + { + EnsureRequestHeaders(settings); + + Uri requestUri = new(new Uri(BASE_URL, UriKind.Absolute), relativeUrl); + + // The metadata endpoints answer with a temporary redirect to the Internet Archive, so the redirect is followed explicitly, which keeps the + // automatic redirects disabled and confines the following to the hosts the Cover Art Archive is allowed to delegate its responses to. + for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++) + { + HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, cancellationToken).ConfigureAwait(false); + + if (!IsRedirect(response.StatusCode) || response.Headers.Location is null) + return response; + + Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location); + // The response of a redirect is not returned, so it must be disposed here to release its connection. + response.Dispose(); + + // A redirect that is not an absolute HTTPS URL, or that points to a host other than the Cover Art Archive or the Internet Archive, is refused, + // so a compromised or misbehaving endpoint cannot redirect the request to any other host. + if (redirectUri is null || redirectUri.Scheme != Uri.UriSchemeHttps || !CoverArtArchiveHosts.IsAllowed(redirectUri.Host)) + throw new HttpRequestException($"The Cover Art Archive redirected the request to the disallowed host '{redirectUri?.Host}'."); + + requestUri = redirectUri; + } + + throw new HttpRequestException("The Cover Art Archive redirected the request too many times."); + } + + /// + /// Sends a GET request to , throttled to respect the configured minimum request interval. + /// Transient failures and rate limiting are retried, so a single hiccup does not surface as a failed resolution. + /// + /// The settings that configure the Cover Art Archive API requests. + /// The absolute URI of the resource to request. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message for the request. + private async Task SendWithRetriesAsync(CoverArtArchiveSettingsDto settings, Uri requestUri, CancellationToken cancellationToken) + { + // A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every + // attempt, so that the retries of a failed request cannot burst past the rate limit of the public service. + for (int attempt = 1; ; attempt++) + { + await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false); + + bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT; + HttpResponseMessage response; + try + { + HttpRequestMessage request = new(HttpMethod.Get, requestUri); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + } + catch (HttpRequestException) when (!isLastAttempt) + { + await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false); + continue; + } + + if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500)) + { + // The delay is read before the response is disposed, because a rate limited response tells the caller how long to wait. + TimeSpan retryDelay = GetRetryDelay(attempt, response); + // The response of a failed attempt is not returned, so it must be disposed here to release its connection. + response.Dispose(); + await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false); + continue; + } + + return response; + } + } + + /// + /// Determines whether the provided status code is a redirect. + /// + /// The status code to check. + /// when the status code is a redirect, otherwise . + private static bool IsRedirect(HttpStatusCode statusCode) + { + return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect; + } + + /// + /// Resolves the location of a redirect against the URI of the request it was returned for. + /// + /// The URI of the request the redirect was returned for. + /// The location of the redirect. + /// The absolute URI of the redirect, or when it could not be resolved. + private static Uri? ResolveRedirect(Uri requestUri, Uri location) + { + if (location.IsAbsoluteUri) + return location; + return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null; + } + + /// + /// Gets the delay to wait before the next attempt, preferring the delay requested by the Cover Art Archive when it is provided. + /// + /// The one based number of the attempt that just failed. + /// The response of the failed attempt, when the failure was a response rather than a transport exception. + /// The delay to wait before the next attempt. + internal static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response) + { + // The delay requested by the response is preferred when it is provided, so the rate limit policy of the Cover Art Archive is honored. + if (response?.Headers.RetryAfter is { } retryAfter) + { + TimeSpan? requestedDelay = retryAfter.Delta; + if (requestedDelay is null && retryAfter.Date is DateTimeOffset date) + { + TimeSpan wait = date - DateTimeOffset.UtcNow; + if (wait > TimeSpan.Zero) + requestedDelay = wait; + } + if (requestedDelay is TimeSpan delay) + { + // A misbehaving server could ask for an extremely long delay, which would stall the scan until it is cancelled, so the wait is capped. + TimeSpan maximumDelay = TimeSpan.FromSeconds(MAXIMUM_RETRY_DELAY_SECONDS); + return delay > maximumDelay ? maximumDelay : delay; + } + } + return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt)); + } + + /// + /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set. + /// + /// The settings that configure the Cover Art Archive API requests. + private void EnsureRequestHeaders(CoverArtArchiveSettingsDto settings) + { + // The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once. + if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0) + { + string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail) + ? settings.UserAgent + : $"{settings.UserAgent} ( {settings.ContactEmail} )"; + _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent); + } + } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveRequestThrottle.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveRequestThrottle.cs new file mode 100644 index 00000000..d347f384 --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveRequestThrottle.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Core.Api; + +/// +/// Class for spacing out the requests sent to the Cover Art Archive API, so the configured minimum request interval is respected across every caller in the process. +/// +internal sealed class CoverArtArchiveRequestThrottle +{ + private readonly SemaphoreSlim _gate = new(1, 1); + + // The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter which caller sends them. + private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue; + + /// + /// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot. + /// + /// The minimum amount of time that must elapse between two consecutive requests. + /// Cancellation token that can be used to stop the execution. + /// A task that completes once the caller may send its request. + public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken) + { + // The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the + // previous reserved slot. + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it. + if (minimumRequestInterval > TimeSpan.Zero) + { + DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval; + TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow; + if (delay > TimeSpan.Zero) + await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + } + + _lastRequestAt = DateTimeOffset.UtcNow; + } + finally + { + _gate.Release(); + } + } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveResponseCache.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveResponseCache.cs new file mode 100644 index 00000000..c3e407d5 --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveResponseCache.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Core.Api; + +/// +/// In-memory cache of the responses returned by the Cover Art Archive API, keyed by the requested URL. +/// It removes the repeated lookups of the same entity during a run, which is significant because the releases of an edition heavy library share their +/// release groups, and it expires its entries after a bounded time. +/// +internal sealed class CoverArtArchiveResponseCache +{ + /// + /// The maximum number of responses the cache keeps. + /// + internal const int MAXIMUM_ENTRY_COUNT = 20_000; + + /// + /// The maximum total number of characters of the cached response bodies. + /// + internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000; + + /// + /// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the + /// eviction from running on every write once a budget is reached. + /// + private const int TRIM_TARGET_PERCENT = 90; + + private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15); + + private readonly int _maximumEntryCount; + private readonly long _maximumCharacterCount; + private readonly TimeSpan _timeToLive; + private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); + + // The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction + // are guarded by a lock, while reads stay lock free. + private readonly Lock _sizeGate = new(); + private long _cachedCharacterCount; + + // Monotonically increasing insertion stamp, used to evict the oldest entries first. + private long _sequence; + + /// + /// Initializes a new instance of the class with the default budgets and time to live. + /// + public CoverArtArchiveResponseCache() + { + _maximumEntryCount = MAXIMUM_ENTRY_COUNT; + _maximumCharacterCount = MAXIMUM_CHARACTER_COUNT; + _timeToLive = s_timeToLive; + } + + /// + /// Initializes a new instance of the class with the provided budgets and time to live. + /// + /// The maximum number of responses the cache keeps. + /// The maximum total number of characters of the cached response bodies. + /// The amount of time a cached response stays valid. + internal CoverArtArchiveResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive) + { + _maximumEntryCount = maximumEntryCount; + _maximumCharacterCount = maximumCharacterCount; + _timeToLive = timeToLive; + } + + /// + /// Tries to get the cached response body for . + /// + /// The key of the cached response. + /// The cached response body, when found. + /// when an unexpired response was found, otherwise . + public bool TryGet(string key, out string? json) + { + // An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it. + if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow) + { + json = entry.Json; + return true; + } + json = null; + return false; + } + + /// + /// Adds or replaces the cached response body for , then trims the cache back to its budgets. + /// + /// The key of the cached response. + /// The response body to cache. + public void Set(string key, string json) + { + // A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache. + if (json.Length > _maximumCharacterCount) + return; + + lock (_sizeGate) + { + if (_entries.TryRemove(key, out CacheEntry? existing)) + _cachedCharacterCount -= existing.Json.Length; + + _entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence); + _cachedCharacterCount += json.Length; + + if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount) + TrimToBudget(); + } + } + + /// + /// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets. + /// + private void TrimToBudget() + { + DateTime utcNow = DateTime.UtcNow; + bool isOverEntryCount = _entries.Count > _maximumEntryCount; + bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount; + int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100); + long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100); + + // Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when + // a budget was not exceeded, so the cache keeps reclaiming dead entries. + foreach (KeyValuePair candidate in _entries.OrderBy(entry => entry.Value.Sequence)) + { + bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow; + bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget; + bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget; + if (!isExpired && !needsEntryTrim && !needsCharacterTrim) + break; + + if (_entries.TryRemove(candidate.Key, out CacheEntry? removed)) + _cachedCharacterCount -= removed.Json.Length; + } + } + + private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence); +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveAlbumArtworkProvider.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveAlbumArtworkProvider.cs new file mode 100644 index 00000000..ffa4422d --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveAlbumArtworkProvider.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using Lumina.Plugins.CoverArtArchive.Core.Api; +using Lumina.Plugins.CoverArtArchive.Core.Mapping; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Core; + +/// +/// Provides the artwork of an album from the Cover Art Archive, by resolving the MusicBrainz identifiers of the album into artwork DTOs. +/// The artwork of the exact release is preferred, and the artwork of its release group is used when the release itself carries none. +/// +internal sealed class CoverArtArchiveAlbumArtworkProvider : IArtworkProvider +{ + private readonly CoverArtArchiveHttpClient _coverArtArchiveHttpClient; + + /// + /// Gets the display name of the artwork provider. + /// + public string Name => "Cover Art Archive"; + + /// + /// Gets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess => true; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP client used to call the Cover Art Archive API. + public CoverArtArchiveAlbumArtworkProvider(CoverArtArchiveHttpClient coverArtArchiveHttpClient) + { + _coverArtArchiveHttpClient = coverArtArchiveHttpClient; + } + + /// + /// Gets the artworks of the album described by . + /// + /// The lookup describing the album to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artworks of the album, or an empty collection when no artwork was found. + public async Task> GetArtworkAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + CoverArtArchiveArtworkResponse? artwork = null; + + // The identifier of the exact release pins the edition the local files match, so its artwork is preferred. + if (lookup.MusicBrainzReleaseId is not null) + artwork = await _coverArtArchiveHttpClient.GetReleaseArtworkAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false); + + // A release can carry no artwork of its own while its release group does, so the release group is the fallback. + // The collection is guarded here too, because the deserializer can produce a null collection regardless of the initializer. + if ((artwork?.Images is null || artwork.Images.Count == 0) && lookup.MusicBrainzReleaseGroupId is not null) + artwork = await _coverArtArchiveHttpClient.GetReleaseGroupArtworkAsync(lookup.MusicBrainzReleaseGroupId.Value, cancellationToken).ConfigureAwait(false); + + return CoverArtArchiveMapper.MapArtwork(artwork); + } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveHosts.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveHosts.cs new file mode 100644 index 00000000..68813e95 --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchiveHosts.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Core; + +/// +/// Defines the hosts of the Cover Art Archive and the Internet Archive, which are the only hosts the plugin queries, the only hosts it may follow a +/// redirect to, and the only hosts it may fetch artwork from. The Cover Art Archive is not self hostable, so no other host can be a legitimate source. +/// +internal static class CoverArtArchiveHosts +{ + /// + /// Determines whether the provided host is one of the hosts the Cover Art Archive may delegate its responses to. + /// + /// The host to check. + /// when the host is allowed, otherwise . + public static bool IsAllowed(string host) + { + return host.Equals("coverartarchive.org", StringComparison.OrdinalIgnoreCase) + || host.EndsWith(".coverartarchive.org", StringComparison.OrdinalIgnoreCase) + || host.Equals("archive.org", StringComparison.OrdinalIgnoreCase) + || host.EndsWith(".archive.org", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchivePlugin.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchivePlugin.cs new file mode 100644 index 00000000..32db69c4 --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/CoverArtArchivePlugin.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.CoverArtArchive.Common.DependencyInjection; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Core; + +/// +/// Plugin that provides music album artwork retrieval from the Cover Art Archive. +/// +public sealed class CoverArtArchivePlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "Cover Art Archive"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Retrieves the cover, back, booklet, medium and other artwork of music albums from the Cover Art Archive."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return + [ + new PluginSettingDescriptorDto( + Key: CoverArtArchiveSettingsKeys.CONTACT_EMAIL, + Label: "Contact Email", + Type: PluginSettingType.Text), + new PluginSettingDescriptorDto( + Key: CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, + Label: "Minimum Request Interval (seconds)", + Type: PluginSettingType.Number, + DefaultValue: "1.0") + ]; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddCoverArtArchiveArtworkProvider(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Mapping/CoverArtArchiveMapper.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Mapping/CoverArtArchiveMapper.cs new file mode 100644 index 00000000..c1852ae9 --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Mapping/CoverArtArchiveMapper.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Core.Mapping; + +/// +/// Maps the responses of the Cover Art Archive API into artwork DTOs. +/// +internal static class CoverArtArchiveMapper +{ + /// + /// Maps the artwork carried by into artwork DTOs, one for every type each image is tagged with. + /// + /// The artwork response to map. + /// The mapped artworks, ordered as they appear in the response, or an empty collection when there is no artwork. + public static IReadOnlyList MapArtwork(CoverArtArchiveArtworkResponse? response) + { + // The collection and its elements are guarded, because the deserializer can produce a null collection, or null elements, regardless of the initializers. + if (response?.Images is null) + return []; + + List artworks = []; + // The ordinals are tracked per type, so that multiple images of the same type, like the pages of a booklet, are ordered among themselves. + Dictionary nextOrdinals = []; + foreach (CoverArtArchiveImageResponse? image in response.Images) + { + if (image is null || !TryResolveArtworkUrl(image.Image, out string artworkUrl)) + continue; + + foreach (ArtworkType artworkType in ResolveArtworkTypes(image)) + { + int ordinal = nextOrdinals.TryGetValue(artworkType, out int nextOrdinal) ? nextOrdinal : 0; + nextOrdinals[artworkType] = ordinal + 1; + artworks.Add(new ArtworkDto(artworkType, ordinal, LocalPath: null, RemoteUrl: artworkUrl)); + } + } + return artworks; + } + + /// + /// Resolves the URL of an artwork image, keeping it only when it points, over an encrypted connection, at a host the Cover Art Archive may serve + /// artwork from. An image URL of any other shape or host is dropped, so a compromised response cannot make the host download from an internal address. + /// + /// The image URL carried by the response. + /// The resolved, encrypted image URL, when it is usable. + /// when the image URL is usable, otherwise . + private static bool TryResolveArtworkUrl(string? candidate, out string artworkUrl) + { + artworkUrl = string.Empty; + if (string.IsNullOrWhiteSpace(candidate)) + return false; + + if (!Uri.TryCreate(candidate.Trim(), UriKind.Absolute, out Uri? uri) || !CoverArtArchiveHosts.IsAllowed(uri.Host)) + return false; + + // The artwork is always fetched over an encrypted connection, so a plain HTTP reference to a trusted host is upgraded to HTTPS, + // and a reference that uses any other scheme is dropped. + if (uri.Scheme == Uri.UriSchemeHttps) + artworkUrl = uri.AbsoluteUri; + else if (uri.Scheme == Uri.UriSchemeHttp) + artworkUrl = new UriBuilder(uri) { Scheme = Uri.UriSchemeHttps, Port = -1 }.Uri.AbsoluteUri; + else + return false; + + return true; + } + + /// + /// Resolves the artwork types an image is tagged with, falling back to the front and back flags when the image carries no type. + /// + /// The image whose types are resolved. + /// The distinct artwork types of the image, in the order they appear in the response. + private static List ResolveArtworkTypes(CoverArtArchiveImageResponse image) + { + // A list de-duplicated on insertion keeps the order of the response, unlike a set, whose iteration order is not deterministic. + List artworkTypes = []; + // The collection and its elements are guarded, because the deserializer can produce a null collection, or null elements, regardless of the initializers. + foreach (string? type in image.Types ?? []) + if (TryMapArtworkType(type, out ArtworkType artworkType) && !artworkTypes.Contains(artworkType)) + artworkTypes.Add(artworkType); + + // An image that carries no known type still describes the front or the back of the release when it is flagged as such. + if (artworkTypes.Count == 0) + { + if (image.IsFront) + artworkTypes.Add(ArtworkType.Cover); + if (image.IsBack) + artworkTypes.Add(ArtworkType.Back); + } + return artworkTypes; + } + + /// + /// Maps a Cover Art Archive image type onto an artwork type. + /// + /// The Cover Art Archive image type. + /// The mapped artwork type, when the type is recognized. + /// when the type was recognized, otherwise . + private static bool TryMapArtworkType(string? type, out ArtworkType artworkType) + { + if (string.IsNullOrWhiteSpace(type)) + { + artworkType = ArtworkType.Other; + return false; + } + + switch (type.Trim().ToLowerInvariant()) + { + case "front": + artworkType = ArtworkType.Cover; + return true; + case "back": + artworkType = ArtworkType.Back; + return true; + case "booklet": + artworkType = ArtworkType.Booklet; + return true; + case "medium": + artworkType = ArtworkType.Medium; + return true; + case "tray": + artworkType = ArtworkType.Tray; + return true; + case "spine": + artworkType = ArtworkType.Spine; + return true; + case "obi": + artworkType = ArtworkType.Obi; + return true; + case "sticker": + artworkType = ArtworkType.Sticker; + return true; + case "poster": + artworkType = ArtworkType.Poster; + return true; + case "liner": + artworkType = ArtworkType.Liner; + return true; + case "watermark": + artworkType = ArtworkType.Watermark; + return true; + default: + // The Cover Art Archive also uses a free form "Other" type and may add new types over time, which are all kept as generic artwork. + artworkType = ArtworkType.Other; + return true; + } + } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsKeys.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsKeys.cs new file mode 100644 index 00000000..bc41419e --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsKeys.cs @@ -0,0 +1,17 @@ +namespace Lumina.Plugins.CoverArtArchive.Core.Settings; + +/// +/// Keys of the settings of the Cover Art Archive artwork plugin, shared by the settings schema and the settings loader. +/// +internal static class CoverArtArchiveSettingsKeys +{ + /// + /// The key of the setting defining the contact email sent to the Cover Art Archive API. + /// + internal const string CONTACT_EMAIL = "ContactEmail"; + + /// + /// The key of the setting defining the minimum interval between consecutive requests to the Cover Art Archive API, in seconds. + /// + internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds"; +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsProvider.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsProvider.cs new file mode 100644 index 00000000..aed1deff --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Settings/CoverArtArchiveSettingsProvider.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Core.Settings; + +/// +/// Provides the runtime settings of the Cover Art Archive artwork plugin, overlaying the settings persisted by the host over the configured defaults. +/// +internal sealed class CoverArtArchiveSettingsProvider +{ + // The minimum request interval is clamped to a sane range, so a persisted value can neither be a non finite value that cannot be turned into a + // duration, nor be so large that waiting for it overflows the delay of the requests. + private const double MAXIMUM_REQUEST_INTERVAL_SECONDS = 60; + + private readonly IPluginSettingsStore? _settingsStore; + private readonly Guid _pluginId; + private readonly CoverArtArchiveSettingsDto _defaults; + + // The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already + // resolved path lock free; the gate is only needed by the first callers that race to resolve it. + private readonly SemaphoreSlim _gate = new(1, 1); + private CoverArtArchiveSettingsDto? _runtimeSettings; + + /// + /// Initializes a new instance of the class. + /// + /// The store of the settings persisted by the host, or when no store is available. + /// The unique identifier of the plugin whose settings are read. + /// The runtime settings with the default values and the optional configuration callback already applied. + public CoverArtArchiveSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, CoverArtArchiveSettingsDto defaults) + { + _settingsStore = settingsStore; + _pluginId = pluginId; + _defaults = defaults; + } + + /// + /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call. + /// + /// Cancellation token that can be used to stop the execution. + /// The runtime settings of the plugin. + public async Task GetAsync(CancellationToken cancellationToken) + { + // Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact. + CoverArtArchiveSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is not null) + return runtimeSettings; + + // Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once. + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // Second check inside the gate: another caller may have resolved the settings while this one was waiting for it. + runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is null) + { + runtimeSettings = await ResolveAsync(cancellationToken).ConfigureAwait(false); + // Publishing through Volatile makes the fully built instance visible to the lock free readers above. + Volatile.Write(ref _runtimeSettings, runtimeSettings); + } + + return runtimeSettings; + } + finally + { + _gate.Release(); + } + } + + /// + /// Builds the runtime settings by overlaying the settings persisted by the host over the configured defaults. + /// + /// Cancellation token that can be used to stop the execution. + /// The runtime settings of the plugin. + private async Task ResolveAsync(CancellationToken cancellationToken) + { + // The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes. + CoverArtArchiveSettingsDto runtimeSettings = new() + { + UserAgent = _defaults.UserAgent, + ContactEmail = _defaults.ContactEmail, + MinimumRequestInterval = _defaults.MinimumRequestInterval + }; + + if (_settingsStore is null) + return runtimeSettings; + + IReadOnlyDictionary? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false); + if (storedSettings is null) + return runtimeSettings; + + if (storedSettings.TryGetValue(CoverArtArchiveSettingsKeys.CONTACT_EMAIL, out string? contactEmail)) + { + string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim(); + runtimeSettings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null; + } + + // A persisted value that is not a finite number is rejected, and a finite one is clamped, so that neither a NaN, nor an infinity, nor an + // out of range value can make the conversion to a duration or the waiting for it throw. + if (storedSettings.TryGetValue(CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) && + double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue) && + double.IsFinite(minimumRequestIntervalValue)) + runtimeSettings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Clamp(minimumRequestIntervalValue, 0, MAXIMUM_REQUEST_INTERVAL_SECONDS)); + + return runtimeSettings; + } + + /// + /// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header. + /// + /// The persisted contact email. + /// when the email is safe, otherwise . + private static bool IsSafeContactEmail(string contactEmail) + { + // The email is embedded in the User-Agent header, and an invalid character there throws when the header is parsed, which would break every request of the plugin, + // so, anything outside a conservative email charset is rejected. + foreach (char character in contactEmail) + if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+')) + return false; + return true; + } +} diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Lumina.Plugins.CoverArtArchive.csproj b/plugins/Lumina.Plugins.CoverArtArchive/Lumina.Plugins.CoverArtArchive.csproj new file mode 100644 index 00000000..bed7d79c --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Lumina.Plugins.CoverArtArchive.csproj @@ -0,0 +1,34 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + + + + + + + + + + + + + + false + runtime + + + + + + + diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.CoverArtArchive/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..575f39dd --- /dev/null +++ b/plugins/Lumina.Plugins.CoverArtArchive/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.SecurityTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.Fixtures")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/plugins/Lumina.Plugins.ID3/Common/DependencyInjection/Id3Services.cs b/plugins/Lumina.Plugins.ID3/Common/DependencyInjection/Id3Services.cs new file mode 100644 index 00000000..6b7ab3cc --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Common/DependencyInjection/Id3Services.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +#endregion + +namespace Lumina.Plugins.ID3.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the ID3 metadata provider into the Dependency Injection container. +/// +internal static class Id3Services +{ + /// + /// Registers the services of the ID3 metadata providers into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the metadata. + /// The updated . + internal static IServiceCollection AddId3MetadataProviders(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // The reader is scoped, so that the tags of a single file are read only once across the artist, album and track providers of the same enrichment scope. + services.TryAddScoped(); + + // Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations. + // A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair. + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs b/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs new file mode 100644 index 00000000..02897507 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs @@ -0,0 +1,258 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.ID3.Common.Models.DTO.Tags; + +/// +/// Snapshot of the metadata read from the embedded tags of a single audio file. +/// Every audio property that the tags do not carry is left empty, so that the local values already extracted from the file are never overwritten with blanks. +/// +internal sealed class Id3TagDto +{ + /// + /// Gets or initializes the title of the track. + /// + public string? Title { get; init; } + + /// + /// Gets or initializes the title of the album the track belongs to. + /// + public string? Album { get; init; } + + /// + /// Gets or initializes the artists credited on the track. + /// + public List TrackArtists { get; init; } = []; + + /// + /// Gets or initializes the artists credited on the album. + /// + public List AlbumArtists { get; init; } = []; + + /// + /// Gets or initializes the sort name of the album artist. + /// + public string? AlbumArtistSortName { get; init; } + + /// + /// Gets or initializes the sort name of the track artist. + /// + public string? TrackArtistSortName { get; init; } + + /// + /// Gets or initializes the number of the track on its disc. + /// + public uint TrackNumber { get; init; } + + /// + /// Gets or initializes the number of tracks on the disc, as reported by the tags. + /// + public uint TrackCount { get; init; } + + /// + /// Gets or initializes the number of the disc the track belongs to. + /// + public uint DiscNumber { get; init; } + + /// + /// Gets or initializes the number of discs of the release, as reported by the tags. + /// + public uint DiscCount { get; init; } + + /// + /// Gets or initializes the year the track was released. + /// + public int? Year { get; init; } + + /// + /// Gets or initializes the original release date of the track. + /// + public DateOnly? OriginalReleaseDate { get; init; } + + /// + /// Gets or initializes the original release year of the track. + /// + public int? OriginalReleaseYear { get; init; } + + /// + /// Gets or initializes the genres the tags associate with the track. + /// + public List Genres { get; init; } = []; + + /// + /// Gets or initializes the composers credited on the track. + /// + public List Composers { get; init; } = []; + + /// + /// Gets or initializes the lyricists credited on the track. + /// + public List Lyricists { get; init; } = []; + + /// + /// Gets or initializes the conductors credited on the track. + /// + public List Conductors { get; init; } = []; + + /// + /// Gets or initializes the remixers credited on the track. + /// + public List Remixers { get; init; } = []; + + /// + /// Gets or initializes the people credited on the track, each with the free-form role read from the tags. + /// + public List<(string Role, string Name)> InvolvedPeople { get; init; } = []; + + /// + /// Gets or initializes the language of the track. + /// + public string? Language { get; init; } + + /// + /// Gets or initializes the script used by the language of the track. + /// + public string? Script { get; init; } + + /// + /// Gets or initializes the label that issued the album. + /// + public string? Label { get; init; } + + /// + /// Gets or initializes the catalog numbers of the album. + /// + public List CatalogNumbers { get; init; } = []; + + /// + /// Gets or initializes the barcode of the album. + /// + public string? Barcode { get; init; } + + /// + /// Gets or initializes the types of the release, as read from the tags. + /// + public List ReleaseTypes { get; init; } = []; + + /// + /// Gets or initializes the status of the release. + /// + public string? ReleaseStatus { get; init; } + + /// + /// Gets or initializes the country the release was issued in. + /// + public string? ReleaseCountry { get; init; } + + /// + /// Gets or initializes the physical or digital medium of the release. + /// + public string? MediaFormat { get; init; } + + /// + /// Gets or initializes the outermost packaging of the release. + /// + public string? Packaging { get; init; } + + /// + /// Gets or initializes the ASIN of the album. + /// + public string? Asin { get; init; } + + /// + /// Gets or initializes the ISRCs of the track. + /// + public List Isrcs { get; init; } = []; + + /// + /// Gets or initializes the moods of the track. + /// + public List Moods { get; init; } = []; + + /// + /// Gets or initializes the title of the work the track is a recording of. + /// + public string? WorkTitle { get; init; } + + /// + /// Gets or initializes the musical key of the track. + /// + public string? MusicKey { get; init; } + + /// + /// Gets or initializes the tempo of the track in beats per minute. + /// + public int? Bpm { get; init; } + + /// + /// Gets or initializes the duration of the audio of the track in seconds. + /// + public int? DurationInSeconds { get; init; } + + /// + /// Gets or initializes the sample rate of the audio of the track in Hz. + /// + public int? SampleRate { get; init; } + + /// + /// Gets or initializes the number of audio channels of the track. + /// + public int? Channels { get; init; } + + /// + /// Gets or initializes the bit depth of the audio of the track. + /// + public int? BitDepth { get; init; } + + /// + /// Gets or initializes the bitrate of the audio of the track in kbps. + /// + public int? Bitrate { get; init; } + + /// + /// Gets or initializes the description of the audio codec of the track. + /// + public string? AudioCodec { get; init; } + + /// + /// Gets or initializes the official website associated with the artist. + /// + public string? Website { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the artist. + /// + public string? MusicBrainzArtistId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the release artist. + /// + public string? MusicBrainzReleaseArtistId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the release group. + /// + public string? MusicBrainzReleaseGroupId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the release. + /// + public string? MusicBrainzReleaseId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the recording of the track. + /// + public string? MusicBrainzRecordingId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the track on its release. + /// + public string? MusicBrainzReleaseTrackId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the work the track is a recording of. + /// + public string? MusicBrainzWorkId { get; init; } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Id3AlbumMetadataProvider.cs b/plugins/Lumina.Plugins.ID3/Core/Id3AlbumMetadataProvider.cs new file mode 100644 index 00000000..4dba963f --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Id3AlbumMetadataProvider.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Mapping; +using Lumina.Plugins.ID3.Core.Tags; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.Core; + +/// +/// Provides album metadata from the embedded tags of one of its audio files, by resolving lookups into album metadata DTOs. +/// +internal sealed class Id3AlbumMetadataProvider : IMetadataProvider +{ + private readonly Id3TagReader _tagReader; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "ID3"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => false; + + /// + /// Initializes a new instance of the class. + /// + /// The reader of the embedded tags of the audio files. + public Id3AlbumMetadataProvider(Id3TagReader tagReader) + { + _tagReader = tagReader; + } + + /// + /// Searches for the metadata of the album described by . + /// + /// The lookup describing the album to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of album metadata candidates found, which for embedded tags is at most the file of the lookup. + public async Task> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + AlbumMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false); + IReadOnlyList results = metadata is null ? [] : [metadata]; + return results; + } + + /// + /// Gets the metadata of the album described by . + /// + /// The lookup describing the album to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the album, or when the file carries none. + public Task GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + return ReadMetadataAsync(lookup.Path, cancellationToken); + } + + /// + /// Reads the metadata of the album from the embedded tags of the track stored at . + /// + /// The file system path of a track of the album. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the album, or when the tags carry no album title. + private Task ReadMetadataAsync(string path, CancellationToken cancellationToken) + { + // The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file. + return Task.Run(() => + { + Id3TagDto? data = _tagReader.Read(path); + if (data is null || string.IsNullOrWhiteSpace(data.Album)) + return null; + return Id3TagMapper.MapAlbum(data); + }, cancellationToken); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Id3ArtistMetadataProvider.cs b/plugins/Lumina.Plugins.ID3/Core/Id3ArtistMetadataProvider.cs new file mode 100644 index 00000000..c0a34ad0 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Id3ArtistMetadataProvider.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Mapping; +using Lumina.Plugins.ID3.Core.Tags; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.Core; + +/// +/// Provides music artist metadata from the embedded tags of one of its audio files, by resolving lookups into artist metadata DTOs. +/// +internal sealed class Id3ArtistMetadataProvider : IMetadataProvider +{ + private readonly Id3TagReader _tagReader; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "ID3"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => false; + + /// + /// Initializes a new instance of the class. + /// + /// The reader of the embedded tags of the audio files. + public Id3ArtistMetadataProvider(Id3TagReader tagReader) + { + _tagReader = tagReader; + } + + /// + /// Searches for the metadata of the artist described by . + /// + /// The lookup describing the artist to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of artist metadata candidates found, which for embedded tags is at most the file of the lookup. + public async Task> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + ArtistMetadataDto? metadata = await ReadMetadataAsync(lookup, cancellationToken).ConfigureAwait(false); + IReadOnlyList results = metadata is null ? [] : [metadata]; + return results; + } + + /// + /// Gets the metadata of the artist described by . + /// + /// The lookup describing the artist to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the artist, or when the file carries none. + public Task GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + return ReadMetadataAsync(lookup, cancellationToken); + } + + /// + /// Reads the metadata of the artist described by from the embedded tags of the track stored at its path. + /// + /// The lookup describing the artist. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the artist, or when the tags carry no artist name. + private Task ReadMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + // The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file. + return Task.Run(() => + { + Id3TagDto? data = _tagReader.Read(lookup.Path); + if (data is null || (data.AlbumArtists.Count == 0 && data.TrackArtists.Count == 0)) + return null; + return Id3TagMapper.MapArtist(data, lookup.Name); + }, cancellationToken); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Id3Plugin.cs b/plugins/Lumina.Plugins.ID3/Core/Id3Plugin.cs new file mode 100644 index 00000000..1492df15 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Id3Plugin.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.ID3.Common.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.ID3.Core; + +/// +/// Plugin that populates music metadata exclusively from the embedded tags of the audio files, without accessing the web. +/// +public sealed class Id3Plugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("a3f1c8d2-6b47-4e9a-8c15-2d7f9e4b6a03"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "ID3 Metadata"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Populates artist, album and track metadata from the embedded tags of the audio files, without accessing the web."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return []; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddId3MetadataProviders(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Id3TrackMetadataProvider.cs b/plugins/Lumina.Plugins.ID3/Core/Id3TrackMetadataProvider.cs new file mode 100644 index 00000000..da604fcc --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Id3TrackMetadataProvider.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Mapping; +using Lumina.Plugins.ID3.Core.Tags; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.Core; + +/// +/// Provides track metadata from the embedded tags of the audio file, by resolving lookups into audio metadata DTOs. +/// +internal sealed class Id3TrackMetadataProvider : IMetadataProvider +{ + private readonly Id3TagReader _tagReader; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "ID3"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => false; + + /// + /// Initializes a new instance of the class. + /// + /// The reader of the embedded tags of the audio files. + public Id3TrackMetadataProvider(Id3TagReader tagReader) + { + _tagReader = tagReader; + } + + /// + /// Searches for the metadata of the track described by . + /// + /// The lookup describing the track to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of track metadata candidates found, which for embedded tags is at most the file of the lookup. + public async Task> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + AudioMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false); + IReadOnlyList results = metadata is null ? [] : [metadata]; + return results; + } + + /// + /// Gets the metadata of the track described by . + /// + /// The lookup describing the track to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the track, or when the file carries none. + public Task GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + return ReadMetadataAsync(lookup.Path, cancellationToken); + } + + /// + /// Reads the metadata of the track stored at from its embedded tags. + /// + /// The file system path of the track. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the track, or when the tags carry no title. + private Task ReadMetadataAsync(string path, CancellationToken cancellationToken) + { + // The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file. + return Task.Run(() => + { + Id3TagDto? data = _tagReader.Read(path); + if (data is null || string.IsNullOrWhiteSpace(data.Title)) + return null; + return Id3TagMapper.MapTrack(data); + }, cancellationToken); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs b/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs new file mode 100644 index 00000000..df197b9a --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs @@ -0,0 +1,644 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.Core.Mapping; + +/// +/// Maps the metadata read from the embedded tags of an audio file into the application's media metadata DTOs. +/// +internal static class Id3TagMapper +{ + /// + /// The neutral cultures of the application, keyed by both their two letter and three letter language codes, so that a language code is resolved without enumerating the cultures of the system for every mapped file. + /// + private static readonly Dictionary s_culturesByLanguageCode = BuildCulturesByLanguageCode(); + + /// + /// Builds the map of the neutral cultures of the application, keyed by their language codes. + /// + /// The cultures, keyed by both their two letter and three letter language codes. + private static Dictionary BuildCulturesByLanguageCode() + { + Dictionary cultures = new(StringComparer.OrdinalIgnoreCase); + foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) + { + if (culture.ThreeLetterISOLanguageName.Length == 3 && !cultures.ContainsKey(culture.ThreeLetterISOLanguageName)) + cultures[culture.ThreeLetterISOLanguageName] = culture; + if (culture.TwoLetterISOLanguageName.Length == 2 && !cultures.ContainsKey(culture.TwoLetterISOLanguageName)) + cultures[culture.TwoLetterISOLanguageName] = culture; + } + return cultures; + } + + /// + /// Maps the tags of an audio file into artist metadata. + /// + /// The tags of a track of the artist. + /// The name of the artist the metadata is mapped for, when known, used to select the matching credited artist. + /// The mapped artist metadata. + public static ArtistMetadataDto MapArtist(Id3TagDto data, string? artistName) + { + bool doesMatchTrackArtist = !string.IsNullOrWhiteSpace(artistName) && data.TrackArtists.Any(artist => string.Equals(artist, artistName, StringComparison.OrdinalIgnoreCase)); + bool doesMatchAlbumArtist = !string.IsNullOrWhiteSpace(artistName) && data.AlbumArtists.Any(artist => string.Equals(artist, artistName, StringComparison.OrdinalIgnoreCase)); + + string? mappedName; + string? mappedSortName; + Guid? musicBrainzArtistId; + if (doesMatchTrackArtist) + { + mappedName = NullIfWhiteSpace(artistName); + mappedSortName = data.TrackArtistSortName ?? data.AlbumArtistSortName; + musicBrainzArtistId = ParseGuid(data.MusicBrainzArtistId) ?? ParseGuid(data.MusicBrainzReleaseArtistId); + } + else if (doesMatchAlbumArtist) + { + mappedName = NullIfWhiteSpace(artistName); + mappedSortName = data.AlbumArtistSortName ?? data.TrackArtistSortName; + musicBrainzArtistId = ParseGuid(data.MusicBrainzReleaseArtistId) ?? ParseGuid(data.MusicBrainzArtistId); + } + else + { + mappedName = NullIfWhiteSpace(data.AlbumArtists.FirstOrDefault()) ?? NullIfWhiteSpace(data.TrackArtists.FirstOrDefault()); + mappedSortName = data.AlbumArtistSortName ?? data.TrackArtistSortName; + musicBrainzArtistId = ParseGuid(data.MusicBrainzArtistId) ?? ParseGuid(data.MusicBrainzReleaseArtistId); + } + + return new ArtistMetadataDto( + Name: mappedName, + SortName: mappedSortName, + Disambiguation: null, + Type: null, + Gender: null, + Country: null, + Area: null, + BeginArea: null, + EndArea: null, + LifeSpanBegin: null, + LifeSpanEnd: null, + IsEnded: false, + Website: data.Website, + MusicBrainzArtistId: musicBrainzArtistId, + Ipis: null, + Isnis: null, + Aliases: null, + Genres: null, + Tags: null, + Ratings: null, + Contributors: null); + } + + /// + /// Maps the tags of an audio file into album metadata. + /// + /// The tags of a track of the album. + /// The mapped album metadata. + public static AlbumMetadataDto MapAlbum(Id3TagDto data) + { + return new AlbumMetadataDto( + Title: NullIfWhiteSpace(data.Album), + OriginalTitle: null, + Description: null, + Disambiguation: null, + ReleaseInfo: BuildReleaseInfo(data), + Language: MapLanguage(data.Language), + OriginalLanguage: null, + Tags: null, + Genres: MapGenres(data.Genres), + Script: NullIfWhiteSpace(data.Script), + ReleaseTypes: MapReleaseTypes(data.ReleaseTypes), + ReleaseStatus: MapReleaseStatus(data.ReleaseStatus), + MediaFormat: MapMediaFormat(data.MediaFormat), + Packaging: MapPackaging(data.Packaging), + TotalDiscs: data.DiscCount > 0 ? (int)data.DiscCount : null, + TotalTracks: data.TrackCount > 0 ? (int)data.TrackCount : null, + Barcode: NullIfWhiteSpace(data.Barcode), + CatalogNumbers: data.CatalogNumbers.Count > 0 ? [.. data.CatalogNumbers] : null, + Label: NullIfWhiteSpace(data.Label), + ASIN: NullIfWhiteSpace(data.Asin), + MusicBrainzReleaseId: ParseGuid(data.MusicBrainzReleaseId), + MusicBrainzReleaseGroupId: ParseGuid(data.MusicBrainzReleaseGroupId), + MusicBrainzReleaseArtistId: ParseGuid(data.MusicBrainzReleaseArtistId), + Contributors: MapAlbumContributors(data), + Ratings: null, + ReleaseTitle: null); + } + + /// + /// Maps the tags of an audio file into track metadata. + /// + /// The tags of the track. + /// The mapped track metadata. + public static AudioMetadataDto MapTrack(Id3TagDto data) + { + return new AudioMetadataDto( + Title: NullIfWhiteSpace(data.Title), + OriginalTitle: null, + Description: null, + Disambiguation: null, + ReleaseInfo: BuildReleaseInfo(data), + Language: MapLanguage(data.Language), + OriginalLanguage: null, + Tags: null, + Genres: MapGenres(data.Genres), + Script: NullIfWhiteSpace(data.Script), + Key: MapKey(data.MusicKey), + Bpm: data.Bpm, + IsVideo: false, + Work: MapWork(data), + Isrcs: MapIsrcs(data.Isrcs), + Moods: MapMoods(data.Moods), + DurationInSeconds: data.DurationInSeconds, + SampleRate: data.SampleRate, + Channels: data.Channels, + BitDepth: data.BitDepth, + AudioCodec: NullIfWhiteSpace(data.AudioCodec), + Bitrate: data.Bitrate, + MusicBrainzRecordingId: ParseGuid(data.MusicBrainzRecordingId), + MusicBrainzTrackId: ParseGuid(data.MusicBrainzReleaseTrackId), + Contributors: MapTrackContributors(data), + Ratings: null); + } + + /// + /// Builds the release information of the metadata from the tags, or when the tags carry none of it. + /// + /// The tags of the track. + /// The release information, or when the tags carry no release field. + private static ReleaseInfoDto? BuildReleaseInfo(Id3TagDto data) + { + ReleaseCountry? releaseCountry = MapReleaseCountry(data.ReleaseCountry); + if (data.OriginalReleaseDate is null && data.OriginalReleaseYear is null && releaseCountry is null) + return null; + + return new ReleaseInfoDto( + OriginalReleaseDate: data.OriginalReleaseDate, + OriginalReleaseYear: data.OriginalReleaseYear, + ReReleaseDate: null, + ReReleaseYear: null, + ReleaseCountry: releaseCountry, + ReleaseVersion: null); + } + + /// + /// Maps the work of the track, or when the tags carry none. + /// + /// The tags of the track. + /// The mapped work, or . + private static MusicWorkDto? MapWork(Id3TagDto data) + { + Guid? workId = ParseFirstGuid(data.MusicBrainzWorkId); + string? workTitle = FirstValue(data.WorkTitle); + // The work is only mapped when both its identifier and its title are known, because the domain requires both and would otherwise reject the whole track. + if (workId is null || string.IsNullOrWhiteSpace(workTitle)) + return null; + return new MusicWorkDto( + MusicBrainzWorkId: workId, + Title: workTitle, + Type: null, + Languages: null, + Iswcs: null); + } + + /// + /// Maps the contributors credited on the track, each with its canonical role. + /// + /// The tags of the track. + /// The mapped contributors, or when the tags credit none. + private static List? MapTrackContributors(Id3TagDto data) + { + List contributors = []; + foreach (string artist in data.TrackArtists) + AddContributor(contributors, artist, MediaContributorRole.Performer); + foreach (string composer in data.Composers) + AddContributor(contributors, composer, MediaContributorRole.Composer); + foreach (string lyricist in data.Lyricists) + AddContributor(contributors, lyricist, MediaContributorRole.Lyricist); + foreach (string conductor in data.Conductors) + AddContributor(contributors, conductor, MediaContributorRole.Conductor); + foreach (string remixer in data.Remixers) + AddContributor(contributors, remixer, MediaContributorRole.Remixer); + foreach ((string role, string name) in data.InvolvedPeople) + AddContributor(contributors, name, MapRole(role)); + + return contributors.Count > 0 ? contributors : null; + } + + /// + /// Maps the contributors credited on the album, which the tags only expose as the album artists. + /// + /// The tags of a track of the album. + /// The mapped contributors, or when the tags credit none. + private static List? MapAlbumContributors(Id3TagDto data) + { + List artists = data.AlbumArtists.Count > 0 ? data.AlbumArtists : data.TrackArtists; + List contributors = []; + foreach (string artist in artists) + AddContributor(contributors, artist, MediaContributorRole.Performer); + return contributors.Count > 0 ? contributors : null; + } + + /// + /// Maps the genres of the metadata, without duplicates. + /// + /// The genre names read from the tags. + /// The mapped genres, or when there are none. + private static List? MapGenres(List genres) + { + List result = [.. genres + .Where(genre => !string.IsNullOrWhiteSpace(genre)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(genre => new GenreDto(genre))]; + return result.Count > 0 ? result : null; + } + + /// + /// Maps the moods of the metadata, without duplicates. + /// + /// The mood names read from the tags. + /// The mapped moods, or when there are none. + private static List? MapMoods(List moods) + { + List result = [.. moods + .Where(mood => !string.IsNullOrWhiteSpace(mood)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(mood => new MoodDto(mood))]; + return result.Count > 0 ? result : null; + } + + /// + /// Maps the ISRCs of the track, without duplicates. + /// + /// The ISRC values read from the tags. + /// The mapped ISRCs, or when there are none. + private static List? MapIsrcs(List isrcs) + { + List result = [.. isrcs + .Where(isrc => !string.IsNullOrWhiteSpace(isrc)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(isrc => new IsrcDto(isrc))]; + return result.Count > 0 ? result : null; + } + + /// + /// Maps the types of the release into the application enum, without duplicates. + /// + /// The free-form release types read from the tags. + /// The mapped release types, or when there are none. + private static List? MapReleaseTypes(List releaseTypes) + { + List result = []; + foreach (string releaseType in releaseTypes) + { + MusicReleaseType? mapped = MapReleaseType(releaseType); + if (mapped is not null && !result.Contains(mapped.Value)) + result.Add(mapped.Value); + } + return result.Count > 0 ? result : null; + } + + /// + /// Maps a single free-form release type into the application enum. + /// + /// The release type to map. + /// The mapped release type, or when the type is unknown. + private static MusicReleaseType? MapReleaseType(string? releaseType) + { + if (string.IsNullOrWhiteSpace(releaseType)) + return null; + return releaseType.Trim().ToLowerInvariant() switch + { + "album" => MusicReleaseType.Album, + "single" => MusicReleaseType.Single, + "ep" => MusicReleaseType.Ep, + "broadcast" => MusicReleaseType.Broadcast, + "other" => MusicReleaseType.Other, + "compilation" => MusicReleaseType.Compilation, + "live" => MusicReleaseType.Live, + "soundtrack" => MusicReleaseType.Soundtrack, + "spokenword" => MusicReleaseType.SpokenWord, + "audio drama" => MusicReleaseType.AudioDrama, + "audiobook" => MusicReleaseType.AudioBook, + "demo" => MusicReleaseType.Demo, + "dj-mix" => MusicReleaseType.DjMix, + "field recording" => MusicReleaseType.FieldRecording, + "interview" => MusicReleaseType.Interview, + "mixtape/street" => MusicReleaseType.Mixtape, + "remix" => MusicReleaseType.Remix, + _ => null + }; + } + + /// + /// Maps a free-form release status into the application enum. + /// + /// The release status to map. + /// The mapped release status, or when the status is unknown. + private static MusicReleaseStatus? MapReleaseStatus(string? releaseStatus) + { + if (string.IsNullOrWhiteSpace(releaseStatus)) + return null; + return releaseStatus.Trim().ToLowerInvariant() switch + { + "official" => MusicReleaseStatus.Official, + "promotion" => MusicReleaseStatus.Promotion, + "bootleg" => MusicReleaseStatus.Bootleg, + "pseudo-release" => MusicReleaseStatus.PseudoRelease, + "withdrawn" => MusicReleaseStatus.Withdrawn, + "cancelled" => MusicReleaseStatus.Cancelled, + "expunged" => MusicReleaseStatus.Expunged, + _ => null + }; + } + + /// + /// Maps an ISO 3166-1 alpha-2 country code into the application enum. + /// + /// The country code to map. + /// The mapped release country, or when the code is unknown. + private static ReleaseCountry? MapReleaseCountry(string? country) + { + if (string.IsNullOrWhiteSpace(country)) + return null; + return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null; + } + + /// + /// Maps a free-form media format into the application enum. + /// + /// The media format to map. + /// The mapped media format, or when the format is unknown. + private static MusicMediaFormat? MapMediaFormat(string? mediaFormat) + { + if (string.IsNullOrWhiteSpace(mediaFormat)) + return null; + + string value = mediaFormat.Trim().ToLowerInvariant(); + MusicMediaFormat? mapped = value switch + { + "12\" vinyl" => MusicMediaFormat.Inch12Vinyl, + "10\" vinyl" => MusicMediaFormat.Inch10Vinyl, + "7\" vinyl" => MusicMediaFormat.Inch7Vinyl, + "3\" vinyl" => MusicMediaFormat.Inch3Vinyl, + "vinyl" => MusicMediaFormat.Vinyl, + "cd" => MusicMediaFormat.CD, + "sacd" => MusicMediaFormat.SACD, + "hybrid sacd" => MusicMediaFormat.HybridSACD, + "digital media" => MusicMediaFormat.DigitalMedia, + "cassette" => MusicMediaFormat.Cassette, + "dvd" => MusicMediaFormat.DVD, + "dvd-video" => MusicMediaFormat.DVDVideo, + "dvd-audio" => MusicMediaFormat.DVDAudio, + "blu-ray" => MusicMediaFormat.BluRay, + "minidisc" => MusicMediaFormat.MiniDisc, + "8cm cd" => MusicMediaFormat.Cm8CD, + "dat" => MusicMediaFormat.DAT, + "vinyl disc" => MusicMediaFormat.VinylDisc, + "other" => MusicMediaFormat.Other, + _ => null + }; + if (mapped is not null) + return mapped; + + // Fall back to a direct parse for the values whose free-form name already matches an enum member, ignoring the separators. + string normalized = value.Replace("\"", string.Empty, StringComparison.Ordinal).Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal); + return Enum.TryParse(normalized, ignoreCase: true, out MusicMediaFormat parsed) ? parsed : null; + } + + /// + /// Maps a free-form packaging into the application enum. + /// + /// The packaging to map. + /// The mapped packaging, or when the packaging is unknown. + private static MusicReleasePackaging? MapPackaging(string? packaging) + { + if (string.IsNullOrWhiteSpace(packaging)) + return null; + + string value = packaging.Trim().ToLowerInvariant().Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal).Replace("/", string.Empty, StringComparison.Ordinal); + return Enum.TryParse(value, ignoreCase: true, out MusicReleasePackaging parsed) ? parsed : null; + } + + /// + /// Maps a free-form musical key into the application enum. + /// + /// The musical key to map. + /// The mapped musical key, or when the key is unknown. + private static MusicKey? MapKey(string? musicKey) + { + if (string.IsNullOrWhiteSpace(musicKey)) + return null; + + string value = musicKey.Trim(); + bool isMinor = false; + if (value.EndsWith("minor", StringComparison.OrdinalIgnoreCase)) + { + isMinor = true; + value = value[..^5]; + } + else if (value.EndsWith("major", StringComparison.OrdinalIgnoreCase)) + value = value[..^5]; + else if (value.EndsWith("min", StringComparison.OrdinalIgnoreCase)) + { + isMinor = true; + value = value[..^3]; + } + else if (value.EndsWith("maj", StringComparison.OrdinalIgnoreCase)) + value = value[..^3]; + else if (value.EndsWith("m", StringComparison.OrdinalIgnoreCase)) + { + isMinor = true; + value = value[..^1]; + } + + value = value.Trim().ToUpperInvariant().Replace("\u266f", "#", StringComparison.Ordinal).Replace("\u266d", "B", StringComparison.Ordinal); + return value switch + { + "C" => isMinor ? MusicKey.CMinor : MusicKey.CMajor, + "C#" or "DB" => isMinor ? MusicKey.CSharpMinor : MusicKey.CSharpMajor, + "D" => isMinor ? MusicKey.DMinor : MusicKey.DMajor, + "D#" or "EB" => isMinor ? MusicKey.DSharpMinor : MusicKey.DSharpMajor, + "E" => isMinor ? MusicKey.EMinor : MusicKey.EMajor, + "F" => isMinor ? MusicKey.FMinor : MusicKey.FMajor, + "F#" or "GB" => isMinor ? MusicKey.FSharpMinor : MusicKey.FSharpMajor, + "G" => isMinor ? MusicKey.GMinor : MusicKey.GMajor, + "G#" or "AB" => isMinor ? MusicKey.GSharpMinor : MusicKey.GSharpMajor, + "A" => isMinor ? MusicKey.AMinor : MusicKey.AMajor, + "A#" or "BB" => isMinor ? MusicKey.ASharpMinor : MusicKey.ASharpMajor, + "B" => isMinor ? MusicKey.BMinor : MusicKey.BMajor, + _ => null + }; + } + + /// + /// Maps a free-form ISO 639 language code into language information. + /// + /// The code to map. + /// The mapped language, or when the code is empty. + private static LanguageInfoDto? MapLanguage(string? rawCode) + { + if (string.IsNullOrWhiteSpace(rawCode)) + return null; + + string code = rawCode.Trim().ToLowerInvariant(); + // A language code can list several languages, such as "eng/ara"; the first one is the language of the release. + string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code; + + switch (primaryCode) + { + case "zxx": + return new LanguageInfoDto(primaryCode, "No linguistic content", null); + case "mul": + return new LanguageInfoDto(primaryCode, "Multiple languages", null); + case "und": + return new LanguageInfoDto(primaryCode, "Undetermined", null); + } + + if (s_culturesByLanguageCode.TryGetValue(primaryCode, out CultureInfo? culture)) + return new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName); + return new LanguageInfoDto(primaryCode, primaryCode, null); + } + + /// + /// Maps a free-form contributor role into a canonical media contributor role. + /// + /// The role to map. + /// The mapped contributor role. + private static MediaContributorRole MapRole(string? role) + { + if (string.IsNullOrWhiteSpace(role)) + return MediaContributorRole.Other; + + string value = role.Trim().ToLowerInvariant(); + + // An instrument is more specific than a generic role, so the instruments are matched first. + if (value.Contains("backing vocal", StringComparison.Ordinal)) + return MediaContributorRole.BackingVocals; + if (value.Contains("vocal", StringComparison.Ordinal)) + return MediaContributorRole.Vocals; + if (value.Contains("bass guitar", StringComparison.Ordinal) || value.Contains("electric bass", StringComparison.Ordinal) || string.Equals(value, "bass", StringComparison.Ordinal)) + return MediaContributorRole.BassGuitar; + if (value.Contains("guitar", StringComparison.Ordinal)) + return MediaContributorRole.Guitar; + if (value.Contains("drum", StringComparison.Ordinal) || value.Contains("membranophone", StringComparison.Ordinal)) + return MediaContributorRole.Drums; + if (value.Contains("percussion", StringComparison.Ordinal) || value.Contains("tambourine", StringComparison.Ordinal) || value.Contains("handclap", StringComparison.Ordinal) || value.Contains("stomp", StringComparison.Ordinal)) + return MediaContributorRole.Percussion; + if (value.Contains("keyboard", StringComparison.Ordinal)) + return MediaContributorRole.Keyboards; + if (value.Contains("piano", StringComparison.Ordinal)) + return MediaContributorRole.Piano; + if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal) || value.Contains("sampler", StringComparison.Ordinal)) + return MediaContributorRole.Synthesizer; + if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal)) + return MediaContributorRole.Strings; + if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal)) + return MediaContributorRole.Brass; + if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal)) + return MediaContributorRole.Woodwinds; + + if (value.Contains("executive producer", StringComparison.Ordinal)) + return MediaContributorRole.ExecutiveProducer; + if (value.Contains("producer", StringComparison.Ordinal)) + return MediaContributorRole.Producer; + if (value.Contains("remix", StringComparison.Ordinal)) + return MediaContributorRole.Remixer; + if (value.Contains("engineer", StringComparison.Ordinal) || value.Contains("mastering", StringComparison.Ordinal)) + return MediaContributorRole.Engineer; + if (value.Contains("mix", StringComparison.Ordinal)) + return MediaContributorRole.Mixer; + if (value.Contains("arranger", StringComparison.Ordinal)) + return MediaContributorRole.Arranger; + if (value.Contains("conductor", StringComparison.Ordinal)) + return MediaContributorRole.Conductor; + if (value.Contains("orchestrator", StringComparison.Ordinal)) + return MediaContributorRole.Orchestrator; + if (value.Contains("composer", StringComparison.Ordinal)) + return MediaContributorRole.Composer; + if (value.Contains("lyricist", StringComparison.Ordinal) || value.Contains("librettist", StringComparison.Ordinal)) + return MediaContributorRole.Lyricist; + if (value.Contains("writer", StringComparison.Ordinal) || value.Contains("author", StringComparison.Ordinal)) + return MediaContributorRole.Author; + if (value.Contains("choir", StringComparison.Ordinal) || value.Contains("chorus", StringComparison.Ordinal)) + return MediaContributorRole.Choir; + if (value.Contains("performer", StringComparison.Ordinal) || value.Contains("member of band", StringComparison.Ordinal) || value.Contains("orchestra", StringComparison.Ordinal)) + return MediaContributorRole.Performer; + + return MediaContributorRole.Other; + } + + /// + /// Adds a contributor to the provided list, unless an identical name and role pair is already present. + /// + /// The contributors collected so far. + /// The display name of the contributor. + /// The role the contributor played. + private static void AddContributor(List contributors, string displayName, MediaContributorRole role) + { + if (string.IsNullOrWhiteSpace(displayName)) + return; + if (contributors.Any(contributor => + string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) && + contributor.Role == role)) + return; + contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), null), role)); + } + + /// + /// Parses the provided value as a globally unique identifier. + /// + /// The value to parse. + /// The parsed identifier, or when the value is missing or malformed. + private static Guid? ParseGuid(string? value) + { + return Guid.TryParse(value, out Guid parsed) ? parsed : null; + } + + /// + /// Parses the first globally unique identifier of a value that may hold several slash-separated identifiers. + /// + /// The value to parse. + /// The first parsed identifier, or when the value holds none. + private static Guid? ParseFirstGuid(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + foreach (string candidate in value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + if (Guid.TryParse(candidate, out Guid parsed)) + return parsed; + return null; + } + + /// + /// Gets the first value of a tag that may hold several slash-separated values. + /// + /// The value to read. + /// The first non-empty value, or when the value is empty. + private static string? FirstValue(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + return NullIfWhiteSpace(value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).FirstOrDefault()); + } + + /// + /// Returns the trimmed value, or when the value is empty or white space. + /// + /// The value to process. + /// The trimmed value, or . + private static string? NullIfWhiteSpace(string? value) + { + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs b/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs new file mode 100644 index 00000000..4f86de83 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs @@ -0,0 +1,434 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +#endregion + +namespace Lumina.Plugins.ID3.Core.Tags; + +/// +/// Reads the embedded tags of an audio file into a snapshot, caching the snapshot per path so that the tags of a single file are read only once. +/// +internal sealed class Id3TagReader +{ + /// + /// The container tag types whose extended tags are searched, in the order they are tried. + /// + private static readonly TagLib.TagTypes[] s_extendedTagContainerTypes = [TagLib.TagTypes.Xiph, TagLib.TagTypes.Id3v2, TagLib.TagTypes.Apple, TagLib.TagTypes.Ape]; + + /// + /// The keys of the free-form Apple tags that carry the involved people of a track, paired with the role each of them describes. + /// + private static readonly (string Role, string Key)[] s_appleInvolvedPeopleKeys = + [ + ("performer", "performer"), + ("producer", "PRODUCER"), + ("engineer", "ENGINEER"), + ("mixer", "MIXER"), + ("arranger", "arranger"), + ("writer", "writer") + ]; + + /// + /// Matches a four digit year. + /// + private static readonly Regex s_yearPattern = new(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b", RegexOptions.Compiled); + + /// + /// The maximum number of tag snapshots the cache retains, so that reading a large library does not retain the tags of every file it visits. + /// + private const int MAX_CACHED_SNAPSHOTS = 512; + + private readonly Dictionary _cache = new(StringComparer.Ordinal); + private readonly Queue _cacheOrder = new(); + private readonly Lock _cacheLock = new(); + + /// + /// Reads the embedded tags of the audio file stored at . + /// + /// The file system path of the audio file whose tags are read. + /// The snapshot of the tags, or when the file does not exist or its tags cannot be read. + public Id3TagDto? Read(string path) + { + if (string.IsNullOrWhiteSpace(path)) + return null; + + lock (_cacheLock) + { + if (_cache.TryGetValue(path, out Id3TagDto? cached)) + return cached; + } + + Id3TagDto? data = ReadTagData(path); + // A file whose tags cannot be read is not cached, so that a transient failure does not skip the file for the rest of the scan. + if (data is null) + return null; + + lock (_cacheLock) + { + if (!_cache.ContainsKey(path)) + { + if (_cache.Count >= MAX_CACHED_SNAPSHOTS) + EvictOldestSnapshot(); + _cache[path] = data; + _cacheOrder.Enqueue(path); + } + } + return data; + } + + /// + /// Removes the snapshot that was cached first, keeping the cache within its maximum size. + /// + private void EvictOldestSnapshot() + { + if (_cacheOrder.Count == 0) + return; + string oldestPath = _cacheOrder.Dequeue(); + _cache.Remove(oldestPath); + } + + /// + /// Reads the embedded tags of the audio file stored at into a snapshot. + /// + /// The file system path of the audio file whose tags are read. + /// The snapshot of the tags, or when the file does not exist or its tags cannot be read. + private static Id3TagDto? ReadTagData(string path) + { + // A file whose path cannot be represented by the operating system, or that is not an audio container, yields no metadata rather than an error. + if (!File.Exists(path)) + return null; + + try + { + // A link inside a library root must not cause the tags of a file outside the library to be read. + if (File.GetAttributes(path).HasFlag(FileAttributes.ReparsePoint)) + return null; + + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + TagLib.Tag tag = tagFile.Tag; + TagLib.Properties audioProperties = tagFile.Properties; + List>> extendedFields = BuildExtendedFieldSources(tagFile); + + (DateOnly? releaseDate, int? releaseYear) = ParseDate(GetExtendedField(extendedFields, "TDRC", "DATE")); + (DateOnly? originalDate, int? originalYear) = ParseDate(GetExtendedField(extendedFields, "TDOR", "originaldate", "ORIGINALDATE", "originalyear")); + int? year = releaseYear ?? (tag.Year > 0 ? (int)tag.Year : null); + // The original release date and year must describe the same point in time, so the explicit original date is preferred and the year of the chosen date is used whenever a date is known, rather than the year of the release described by the tags. + DateOnly? originalReleaseDate = originalDate ?? releaseDate; + int? originalReleaseYear = originalReleaseDate?.Year ?? originalYear ?? year; + + return new Id3TagDto + { + Title = NullIfWhiteSpace(tag.Title), + Album = NullIfWhiteSpace(tag.Album), + TrackArtists = Filter(tag.Performers), + AlbumArtists = Filter(tag.AlbumArtists), + AlbumArtistSortName = NullIfWhiteSpace(tag.AlbumArtistsSort?.FirstOrDefault()), + TrackArtistSortName = NullIfWhiteSpace(tag.PerformersSort?.FirstOrDefault()), + TrackNumber = tag.Track, + TrackCount = tag.TrackCount, + DiscNumber = tag.Disc, + DiscCount = tag.DiscCount, + Year = year, + OriginalReleaseDate = originalReleaseDate, + OriginalReleaseYear = originalReleaseYear, + Genres = SplitValues(Filter(tag.Genres)), + Composers = SplitValues(Filter(tag.Composers)), + Lyricists = SplitValues(GetExtendedFields(extendedFields, "LYRICIST", "lyricist", "TEXT")), + Conductors = Filter([tag.Conductor]), + Remixers = Filter([tag.RemixedBy]), + InvolvedPeople = ReadInvolvedPeople(extendedFields), + Language = NullIfWhiteSpace(GetExtendedField(extendedFields, "LANGUAGE", "TLAN")), + Script = NullIfWhiteSpace(GetExtendedField(extendedFields, "SCRIPT")), + Label = NullIfWhiteSpace(tag.Publisher) ?? NullIfWhiteSpace(GetExtendedField(extendedFields, "LABEL")), + CatalogNumbers = SplitValuesOnSemicolons(GetExtendedFields(extendedFields, "CATALOGNUMBER")), + Barcode = NullIfWhiteSpace(GetExtendedField(extendedFields, "BARCODE", "barcode")), + ReleaseTypes = SplitValuesOnSemicolons([tag.MusicBrainzReleaseType]), + ReleaseStatus = NullIfWhiteSpace(tag.MusicBrainzReleaseStatus), + ReleaseCountry = NullIfWhiteSpace(tag.MusicBrainzReleaseCountry), + MediaFormat = NullIfWhiteSpace(GetExtendedField(extendedFields, "MEDIA", "TMED")), + Packaging = NullIfWhiteSpace(GetExtendedField(extendedFields, "PACKAGING")), + Asin = NullIfWhiteSpace(tag.AmazonId) ?? NullIfWhiteSpace(GetExtendedField(extendedFields, "ASIN")), + Isrcs = ReadIsrcs(extendedFields, tag), + Moods = SplitValues(GetExtendedFields(extendedFields, "mood", "MOOD", "MOODS")), + WorkTitle = NullIfWhiteSpace(GetExtendedField(extendedFields, "WORK", "MUSICBRAINZ_WORK")), + MusicKey = NullIfWhiteSpace(tag.InitialKey), + Bpm = tag.BeatsPerMinute > 0 ? (int)tag.BeatsPerMinute : null, + DurationInSeconds = audioProperties.Duration > TimeSpan.Zero ? (int)audioProperties.Duration.TotalSeconds : null, + SampleRate = audioProperties.AudioSampleRate > 0 ? audioProperties.AudioSampleRate : null, + Channels = audioProperties.AudioChannels > 0 ? audioProperties.AudioChannels : null, + BitDepth = audioProperties.BitsPerSample > 0 ? audioProperties.BitsPerSample : null, + Bitrate = audioProperties.AudioBitrate > 0 ? audioProperties.AudioBitrate : null, + AudioCodec = NullIfWhiteSpace(audioProperties.Description), + Website = NullIfWhiteSpace(GetExtendedField(extendedFields, "WOAR", "website")), + MusicBrainzArtistId = NullIfWhiteSpace(tag.MusicBrainzArtistId), + MusicBrainzReleaseArtistId = NullIfWhiteSpace(tag.MusicBrainzReleaseArtistId), + MusicBrainzReleaseGroupId = NullIfWhiteSpace(tag.MusicBrainzReleaseGroupId), + MusicBrainzReleaseId = NullIfWhiteSpace(tag.MusicBrainzReleaseId), + MusicBrainzRecordingId = NullIfWhiteSpace(tag.MusicBrainzTrackId), + MusicBrainzReleaseTrackId = NullIfWhiteSpace(GetExtendedField(extendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")), + MusicBrainzWorkId = NullIfWhiteSpace(GetExtendedField(extendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID")) + }; + } + } + catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException) + { + // A file whose tags cannot be read still contributes the metadata derived from its path, so the failure is not propagated. + return null; + } + } + + /// + /// Reads the people credited on the track, together with the free-form role each of them is credited for. + /// + /// The extended fields of the file, in the order their containers are searched. + /// The people credited on the track, as role and name pairs. + private static List<(string Role, string Name)> ReadInvolvedPeople(List>> extendedFields) + { + List<(string Role, string Name)> people = []; + + // The ID3v2.3 involved people list (IPLS) and the ID3v2.4 equivalent (TIPL) store roles and names as a single flat sequence of alternating values. + List id3People = GetExtendedFields(extendedFields, "IPLS", "TIPL", "TMCL"); + for (int index = 0; index + 1 < id3People.Count; index += 2) + people.Add((id3People[index], id3People[index + 1])); + + // The Apple containers store each role as its own free-form tag, carrying one or more names. + foreach ((string role, string key) in s_appleInvolvedPeopleKeys) + foreach (string name in GetExtendedFields(extendedFields, key)) + if (!string.IsNullOrWhiteSpace(name)) + people.Add((role, name)); + + return people; + } + + /// + /// Reads the ISRCs of the track, from both the dedicated tag and the extended tags, without duplicates. + /// + /// The extended fields of the file, in the order their containers are searched. + /// The combined tag of the file. + /// The ISRCs of the track. + private static List ReadIsrcs(List>> extendedFields, TagLib.Tag tag) + { + List values = SplitValues(GetExtendedFields(extendedFields, "ISRC", "TSRC")); + if (!string.IsNullOrWhiteSpace(tag.ISRC)) + values.AddRange(SplitValues([tag.ISRC])); + return [.. values.Distinct(StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Builds the ordered accessors that resolve an extended tag value from whichever container tag of the file carries it. + /// + /// The file whose extended tags are read. + /// The accessors, in the order the containers are searched. + private static List>> BuildExtendedFieldSources(TagLib.File tagFile) + { + List>> sources = []; + foreach (TagLib.TagTypes tagType in s_extendedTagContainerTypes) + { + TagLib.Tag? tag = tagFile.GetTag(tagType); + if (tag is TagLib.Ogg.XiphComment xiphComment) + sources.Add(key => [.. (xiphComment.GetField(key) ?? [])]); + else if (tag is TagLib.Id3v2.Tag id3v2Tag) + { + Dictionary> id3Fields = BuildId3v2Fields(id3v2Tag); + sources.Add(key => id3Fields.TryGetValue(key, out List? values) ? values : []); + } + else if (tag is TagLib.Mpeg4.AppleTag appleTag) + sources.Add(key => GetAppleFields(appleTag, key)); + else if (tag is TagLib.Ape.Tag apeTag) + sources.Add(key => GetApeFields(apeTag, key)); + } + return sources; + } + + /// + /// Builds the map of the ID3v2 frames of the file, keyed by the name each frame is looked up with, so that the frames are enumerated only once per file. + /// + /// The ID3v2 tag whose frames are indexed. + /// The values of every frame, keyed by the frame identifier or the description of a user defined frame. + private static Dictionary> BuildId3v2Fields(TagLib.Id3v2.Tag id3v2Tag) + { + Dictionary> fields = new(StringComparer.OrdinalIgnoreCase); + foreach (TagLib.Id3v2.Frame frame in id3v2Tag.GetFrames()) + { + string key; + List values; + if (frame is TagLib.Id3v2.UserTextInformationFrame userTextViewFrame) + { + key = userTextViewFrame.Description; + values = [.. userTextViewFrame.Text]; + } + else if (frame is TagLib.Id3v2.UrlLinkFrame urlFrame) + { + key = urlFrame.FrameId.ToString(); + values = [.. urlFrame.Text]; + } + else if (frame is TagLib.Id3v2.TextInformationFrame textFrame) + { + key = textFrame.FrameId.ToString(); + values = [.. textFrame.Text]; + } + else + continue; + + // A user defined frame without a description carries no lookup key, so it is not indexed. + if (string.IsNullOrEmpty(key)) + continue; + + if (fields.TryGetValue(key, out List? existing)) + existing.AddRange(values); + else + fields[key] = values; + } + return fields; + } + + /// + /// Reads the values of a free-form Apple tag with the provided . + /// + /// The Apple tag whose values are read. + /// The name of the free-form tag to read. + /// Every value of the tag. + private static List GetAppleFields(TagLib.Mpeg4.AppleTag appleTag, string key) + { + List values = []; + foreach (string appleValue in appleTag.GetDashBoxes("com.apple.iTunes", key) ?? []) + values.AddRange(appleValue.Split('\0', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + return values; + } + + /// + /// Reads the values of an APE tag with the provided . + /// + /// The APE tag whose values are read. + /// The name of the tag to read. + /// Every value of the tag. + private static List GetApeFields(TagLib.Ape.Tag apeTag, string key) + { + if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem) + return [.. apeItem.ToStringArray()]; + return []; + } + + /// + /// Reads the first non-empty value of an extended tag, from whichever container tag of the file carries it. + /// + /// The extended fields of the file, in the order their containers are searched. + /// The candidate names of the extended tag to read, in the order they are tried. + /// The first non-empty value found, or when the file carries none of the provided tags. + private static string? GetExtendedField(List>> extendedFields, params string[] keys) + { + foreach (Func> extendedField in extendedFields) + { + foreach (string key in keys) + { + List values = extendedField(key); + string? value = values.FirstOrDefault(candidate => !string.IsNullOrWhiteSpace(candidate)); + if (!string.IsNullOrWhiteSpace(value)) + return value; + } + } + return null; + } + + /// + /// Reads every value of an extended tag, from whichever container tag of the file carries it. + /// + /// The extended fields of the file, in the order their containers are searched. + /// The candidate names of the extended tag to read, in the order they are tried. + /// Every non-empty value found, or an empty list when the file carries none of the provided tags. + private static List GetExtendedFields(List>> extendedFields, params string[] keys) + { + List values = []; + foreach (Func> extendedField in extendedFields) + foreach (string key in keys) + // A container whose keys are matched case insensitively resolves several case variant aliases to the same entry, so the values already read are not added again. + foreach (string value in extendedField(key)) + if (!string.IsNullOrWhiteSpace(value) && !values.Contains(value, StringComparer.Ordinal)) + values.Add(value); + return values; + } + + /// + /// Keeps only the non-empty values of the provided collection, trimmed. + /// + /// The values to filter. + /// The non-empty, trimmed values. + private static List Filter(IEnumerable? values) + { + return [.. (values ?? []).Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim())]; + } + + /// + /// Splits every provided value on the separators used to pack several values into a single tag, and keeps the non-empty results. + /// + /// The values to split. + /// The individual values found. + private static List SplitValues(IEnumerable values) + { + return SplitValues(values, ['/', ';']); + } + + /// + /// Splits every provided value on semicolons only, for the tags whose own values may contain a slash. + /// + /// The values to split. + /// The individual values found. + private static List SplitValuesOnSemicolons(IEnumerable values) + { + return SplitValues(values, [';']); + } + + /// + /// Splits every provided value on the provided separators, and keeps the non-empty results. + /// + /// The values to split. + /// The separators to split the values on. + /// The individual values found. + private static List SplitValues(IEnumerable values, char[] separators) + { + List result = []; + foreach (string value in values) + { + if (string.IsNullOrWhiteSpace(value)) + continue; + foreach (string part in value.Split(separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + if (!string.IsNullOrWhiteSpace(part)) + result.Add(part); + } + return result; + } + + /// + /// Parses a date string into a date and a year. + /// + /// The date string to parse. + /// The parsed date and year, or values when the string could not be parsed. + private static (DateOnly? Date, int? Year) ParseDate(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return (null, null); + + if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact)) + return (exact, exact.Year); + + Match yearMatch = s_yearPattern.Match(value); + return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null); + } + + /// + /// Returns the trimmed value, or when the value is empty or white space. + /// + /// The value to process. + /// The trimmed value, or . + private static string? NullIfWhiteSpace(string? value) + { + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Lumina.Plugins.ID3.csproj b/plugins/Lumina.Plugins.ID3/Lumina.Plugins.ID3.csproj new file mode 100644 index 00000000..7ff8f7bd --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Lumina.Plugins.ID3.csproj @@ -0,0 +1,35 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + + + + + + + + + + + + + + false + runtime + + + + + + + + diff --git a/plugins/Lumina.Plugins.ID3/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.ID3/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..08a41295 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.IntegrationTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.Fixtures")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Common/DependencyInjection/LocalMusicArtworkServices.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Common/DependencyInjection/LocalMusicArtworkServices.cs new file mode 100644 index 00000000..8c2b7582 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Common/DependencyInjection/LocalMusicArtworkServices.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the local music artwork providers into the Dependency Injection container. +/// +internal static class LocalMusicArtworkServices +{ + /// + /// Registers the services of the local music artwork providers into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the artwork. + /// The updated . + internal static IServiceCollection AddLocalMusicArtworkProviders(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults. + services.TryAddScoped(serviceProvider => + { + LocalMusicArtworkSettingsDto defaults = new(); + IPluginSettingsStore? settingsStore = serviceProvider.GetService(); + return new LocalMusicArtworkSettingsProvider(settingsStore, pluginId, defaults); + }); + + // Register the artwork providers as keyed by pluginId transient services, so they can be resolved specifically among other IArtworkProvider implementations. + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDto.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDto.cs new file mode 100644 index 00000000..2a9ef3f5 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDto.cs @@ -0,0 +1,13 @@ +namespace Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; + +/// +/// Data transfer object for the settings that configure the local music artwork plugin. +/// +internal sealed class LocalMusicArtworkSettingsDto +{ + /// + /// Gets or sets a value indicating whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// Defaults to , so that a cover is found even when the library stores none on disk. + /// + public bool ShouldExtractEmbeddedCover { get; set; } = true; +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicAlbumArtworkProvider.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicAlbumArtworkProvider.cs new file mode 100644 index 00000000..ef2d8c37 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicAlbumArtworkProvider.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Provides the artwork of an album from the images stored in the folders of the local music library of the user. +/// When the album has no cover image on disk and the settings allow it, the cover embedded in the audio files is extracted as a fallback. +/// +internal sealed class LocalMusicAlbumArtworkProvider : IArtworkProvider +{ + private readonly LocalMusicArtworkSettingsProvider _settingsProvider; + + /// + /// Gets the display name of the artwork provider. + /// + public string Name => "Local Music Artwork"; + + /// + /// Gets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess => false; + + /// + /// Initializes a new instance of the class. + /// + /// The provider of the runtime settings of the plugin. + public LocalMusicAlbumArtworkProvider(LocalMusicArtworkSettingsProvider settingsProvider) + { + _settingsProvider = settingsProvider; + } + + /// + /// Gets the artworks of the album described by . + /// + /// The lookup describing the album to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artworks of the album, or an empty collection when no artwork was found. + public async Task> GetArtworkAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + IReadOnlyList artworks = LocalMusicArtworkScanner.ScanAlbumArtwork(lookup.Path); + + // The cover stored on disk always wins; the embedded one only fills the gap when the album carries no cover on disk at all. + if (artworks.Any(artwork => artwork.Type == ArtworkType.Cover)) + return artworks; + + LocalMusicArtworkSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + if (!settings.ShouldExtractEmbeddedCover) + return artworks; + + ArtworkDto? embeddedCover = LocalMusicArtworkEmbeddedCoverExtractor.Extract(lookup.Path); + if (embeddedCover is null) + return artworks; + return [.. artworks, embeddedCover]; + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtistArtworkProvider.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtistArtworkProvider.cs new file mode 100644 index 00000000..8c6aab35 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtistArtworkProvider.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Provides the artwork of an artist from the images stored in the folders of the local music library of the user. +/// +internal sealed class LocalMusicArtistArtworkProvider : IArtworkProvider +{ + /// + /// Gets the display name of the artwork provider. + /// + public string Name => "Local Music Artwork"; + + /// + /// Gets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess => false; + + /// + /// Gets the artworks of the artist described by . + /// + /// The lookup describing the artist to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artworks of the artist, or an empty collection when no artwork was found. + public Task> GetArtworkAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + return Task.FromResult(LocalMusicArtworkScanner.ScanArtistArtwork(lookup.Path)); + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkEmbeddedCoverExtractor.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkEmbeddedCoverExtractor.cs new file mode 100644 index 00000000..4613a332 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkEmbeddedCoverExtractor.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Extracts the cover image embedded in the metadata of an audio file into a temporary file, so that it can be stored as the artwork of an album. +/// +internal static class LocalMusicArtworkEmbeddedCoverExtractor +{ + private const int MAX_EMBEDDED_COVER_SIZE_BYTES = 10 * 1024 * 1024; // The maximum size of an embedded cover, matching the size limit the artwork storage enforces. + + /// + /// Extracts the first embedded cover image of the audio file stored at into a temporary file. + /// + /// The file system path of the audio file whose embedded cover is extracted. + /// The extracted cover artwork, which points to a temporary file, or when the file carries no usable embedded cover. + public static ArtworkDto? Extract(string? trackPath) + { + if (string.IsNullOrWhiteSpace(trackPath) || !File.Exists(trackPath)) + return null; + + try + { + // A link must not cause the metadata of a file outside the library to be read. + if (File.GetAttributes(trackPath).HasFlag(FileAttributes.ReparsePoint)) + return null; + + using (TagLib.File tagFile = TagLib.File.Create(trackPath)) + { + TagLib.IPicture? cover = tagFile.Tag.Pictures?.FirstOrDefault(picture => picture is not null && picture.Data is not null); + if (cover?.Data is null) + return null; + + byte[] imageBytes = cover.Data.Data; + if (imageBytes is null || imageBytes.Length == 0 || imageBytes.Length > MAX_EMBEDDED_COVER_SIZE_BYTES) + return null; + + string temporaryPath = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artwork-{Guid.NewGuid():N}{ResolveImageExtension(cover.MimeType)}"); + File.WriteAllBytes(temporaryPath, imageBytes); + return new ArtworkDto(ArtworkType.Cover, 0, LocalPath: temporaryPath, RemoteUrl: null, IsTemporary: true); + } + } + catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException) + { + // A file whose embedded cover cannot be read contributes no cover, rather than failing the artwork resolution of the whole album. + return null; + } + } + + /// + /// Resolves the file extension of an embedded cover image from its MIME type. + /// + /// The MIME type of the embedded cover image. + /// The file extension matching the MIME type, falling back to the JPEG extension. + private static string ResolveImageExtension(string? mimeType) + { + return mimeType?.Trim().ToLowerInvariant() switch + { + "image/png" => ".png", + "image/webp" => ".webp", + "image/bmp" or "image/x-ms-bmp" => ".bmp", + "image/gif" => ".gif", + "image/tiff" => ".tiff", + _ => ".jpg" + }; + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkPlugin.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkPlugin.cs new file mode 100644 index 00000000..766d9672 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkPlugin.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Plugin that provides the artwork of music artists and albums from the images stored in the folders of a local music library. +/// +public sealed class LocalMusicArtworkPlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "Local Music Artwork"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Reads the artwork of the artists and the albums from the images stored in the folders of a local music library."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return + [ + new PluginSettingDescriptorDto( + Key: LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER, + Label: "Extract embedded album cover image from audio files when it is not already present on disk", + Type: PluginSettingType.Boolean, + DefaultValue: "true") + ]; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddLocalMusicArtworkProviders(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkScanner.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkScanner.cs new file mode 100644 index 00000000..b7eb16ce --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkScanner.cs @@ -0,0 +1,270 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Scans the folders of a local music library and classifies the images they contain into artwork DTOs, following the naming +/// conventions that music media servers use for the images of an artist and of an album. +/// The file names are matched case sensitively, so that a library that stores them with a different casing is left alone. +/// +internal static class LocalMusicArtworkScanner +{ + private const int MAX_ALBUM_ANCESTOR_LEVELS = 2; // The number of directories, the one of a track and its parent, that are inspected when locating the folder of an album. + private const int MAX_ARTIST_ANCESTOR_LEVELS = 5; // The number of parent directories that are inspected when locating the folder of an artist. + + private static readonly HashSet s_imageExtensions = new([".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif", ".tif", ".tiff"], StringComparer.Ordinal); + + /// + /// Scans the directory of the provided track, and its parent directory, for the artwork of an album. + /// + /// The file system path of a track of the album. + /// The artwork of the album, or an empty collection when no artwork was found. + public static IReadOnlyList ScanAlbumArtwork(string? trackPath) + { + string? trackDirectory = GetDirectoryOrNull(trackPath); + if (trackDirectory is null) + return []; + + // A multi disc album nests its tracks in disc subdirectories, so both the track directory and its parent are inspected, the nearest one taking precedence. + List artworks = []; + HashSet<(ArtworkType Type, int Ordinal)> seenArtworks = []; + DirectoryInfo? currentDirectory = new(trackDirectory); + int level = 0; + while (currentDirectory is not null && level < MAX_ALBUM_ANCESTOR_LEVELS) + { + foreach (ArtworkDto artwork in ClassifyImages(currentDirectory, isArtist: false)) + if (seenArtworks.Add((artwork.Type, artwork.Ordinal))) + artworks.Add(artwork); + currentDirectory = currentDirectory.Parent; + level++; + } + return artworks; + } + + /// + /// Scans the ancestor directories of the provided track for the artwork of an artist. + /// + /// The file system path of a track of the artist. + /// The artwork of the artist, or an empty collection when no artwork was found. + public static IReadOnlyList ScanArtistArtwork(string? trackPath) + { + string? trackDirectory = GetDirectoryOrNull(trackPath); + if (trackDirectory is null) + return []; + + // The artist directory is the nearest ancestor that carries an artist level image, like a folder, a backdrop or a logo. + DirectoryInfo? currentDirectory = new(trackDirectory); + int level = 0; + while (currentDirectory is not null && level < MAX_ARTIST_ANCESTOR_LEVELS) + { + IReadOnlyList artworks = ClassifyImages(currentDirectory, isArtist: true); + if (artworks.Count > 0) + return artworks; + currentDirectory = currentDirectory.Parent; + level++; + } + return []; + } + + /// + /// Classifies the images directly contained in . + /// + /// The directory whose images are classified. + /// Whether the images belong to an artist, as opposed to an album. + /// The classified artwork, one for every recognized file, ordered by type and ordinal. + private static IReadOnlyList ClassifyImages(DirectoryInfo directory, bool isArtist) + { + FileInfo[] files; + try + { + files = [.. directory.EnumerateFiles()]; + } + catch (IOException) + { + return []; + } + catch (UnauthorizedAccessException) + { + return []; + } + + List candidates = []; + foreach (FileInfo file in files) + { + if (!s_imageExtensions.Contains(file.Extension)) + continue; + + (string baseName, int ordinal) = SplitStem(Path.GetFileNameWithoutExtension(file.Name)); + bool isRecognized = isArtist + ? TryMapArtistName(baseName, out ArtworkType artworkType, out int priority) + : TryMapAlbumName(baseName, out artworkType, out priority); + if (!isRecognized) + continue; + candidates.Add(new ClassifiedArtwork(artworkType, ordinal, priority, file.Name, file.FullName)); + } + + // Multiple file names can describe the same piece of artwork, like a cover and a front image, so only the preferred one is kept per type and ordinal. + List artworks = []; + HashSet<(ArtworkType Type, int Ordinal)> seenArtworks = []; + foreach (ClassifiedArtwork candidate in candidates + .OrderBy(candidate => candidate.Type) + .ThenBy(candidate => candidate.Ordinal) + .ThenBy(candidate => candidate.Priority) + .ThenBy(candidate => candidate.FileName, StringComparer.Ordinal)) + { + if (!seenArtworks.Add((candidate.Type, candidate.Ordinal))) + continue; + artworks.Add(new ArtworkDto(candidate.Type, candidate.Ordinal, LocalPath: candidate.FilePath, RemoteUrl: null)); + } + return artworks; + } + + /// + /// Splits the stem of an image file into the base name that identifies the artwork and the ordinal that orders it within its type. + /// + /// The stem of the image file, without its extension. + /// The base name of the artwork and the ordinal it carries, which is zero when the stem carries no number. + private static (string BaseName, int Ordinal) SplitStem(string stem) + { + int index = stem.Length; + while (index > 0 && char.IsAsciiDigit(stem[index - 1])) + index--; + string ordinalPart = stem[index..]; + string baseName = stem[..index].TrimEnd(' ', '-', '_'); + int ordinal = ordinalPart.Length > 0 && int.TryParse(ordinalPart, out int parsedOrdinal) ? parsedOrdinal : 0; + return (baseName, ordinal); + } + + /// + /// Maps the base name of an artist image onto an artwork type. + /// + /// The base name of the image file. + /// The mapped artwork type, when the base name is recognized. + /// The priority of the base name among the file names of the same artwork type and ordinal, lower being preferred. + /// when the base name was recognized, otherwise . + private static bool TryMapArtistName(string baseName, out ArtworkType artworkType, out int priority) + { + priority = 0; + switch (baseName) + { + case "folder": + artworkType = ArtworkType.Cover; + return true; + case "backdrop": + artworkType = ArtworkType.Backdrop; + return true; + case "banner": + artworkType = ArtworkType.Banner; + return true; + case "logo": + artworkType = ArtworkType.Logo; + return true; + case "thumb": + artworkType = ArtworkType.Thumb; + return true; + default: + artworkType = ArtworkType.Other; + priority = int.MaxValue; + return false; + } + } + + /// + /// Maps the base name of an album image onto an artwork type. + /// + /// The base name of the image file. + /// The mapped artwork type, when the base name is recognized. + /// The priority of the base name among the file names of the same artwork type and ordinal, lower being preferred. + /// when the base name was recognized, otherwise . + private static bool TryMapAlbumName(string baseName, out ArtworkType artworkType, out int priority) + { + switch (baseName) + { + case "cover": + artworkType = ArtworkType.Cover; + priority = 0; + return true; + case "front": + artworkType = ArtworkType.Front; + priority = 0; + return true; + case "back": + artworkType = ArtworkType.Back; + priority = 0; + return true; + case "booklet": + artworkType = ArtworkType.Booklet; + priority = 0; + return true; + case "disk": + case "disc": + artworkType = ArtworkType.Medium; + priority = 0; + return true; + case "liner": + artworkType = ArtworkType.Liner; + priority = 0; + return true; + case "tray": + artworkType = ArtworkType.Tray; + priority = 0; + return true; + case "spine": + artworkType = ArtworkType.Spine; + priority = 0; + return true; + case "obi": + artworkType = ArtworkType.Obi; + priority = 0; + return true; + case "sticker": + artworkType = ArtworkType.Sticker; + priority = 0; + return true; + case "poster": + artworkType = ArtworkType.Poster; + priority = 0; + return true; + default: + artworkType = ArtworkType.Other; + priority = int.MaxValue; + return false; + } + } + + /// + /// Gets the directory of the provided . + /// + /// The file system path whose directory is retrieved. + /// The directory of the path, or when the path is empty or has no directory part. + private static string? GetDirectoryOrNull(string? path) + { + if (string.IsNullOrWhiteSpace(path)) + return null; + string? directory = Path.GetDirectoryName(path); + return string.IsNullOrWhiteSpace(directory) ? null : directory; + } + + /// + /// A recognized image of an artist or an album, before it is ordered and de-duplicated. + /// + /// The type of the artwork. + /// The ordinal of the artwork within its type. + /// The priority of the file name among the files of the same artwork type and ordinal, lower being preferred. + /// The name of the image file. + /// The file system path of the image file. + private sealed record ClassifiedArtwork( + ArtworkType Type, + int Ordinal, + int Priority, + string FileName, + string FilePath + ); +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsKeys.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsKeys.cs new file mode 100644 index 00000000..7773c721 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsKeys.cs @@ -0,0 +1,12 @@ +namespace Lumina.Plugins.LocalMusicArtwork.Core.Settings; + +/// +/// Keys of the settings of the local music artwork plugin, shared by the settings schema and the settings provider. +/// +internal static class LocalMusicArtworkSettingsKeys +{ + /// + /// The key of the setting that controls whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// + internal const string SHOULD_EXTRACT_EMBEDDED_COVER = "ShouldExtractEmbeddedCover"; +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsProvider.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsProvider.cs new file mode 100644 index 00000000..c2a5462f --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsProvider.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core.Settings; + +/// +/// Provides the runtime settings of the local music artwork plugin, overlaying the settings persisted by the host over the configured defaults. +/// +internal sealed class LocalMusicArtworkSettingsProvider +{ + private readonly IPluginSettingsStore? _settingsStore; + private readonly Guid _pluginId; + private readonly LocalMusicArtworkSettingsDto _defaults; + + // The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already + // resolved path lock free; the gate is only needed by the first callers that race to resolve it. + private readonly SemaphoreSlim _gate = new(1, 1); + private LocalMusicArtworkSettingsDto? _runtimeSettings; + + /// + /// Initializes a new instance of the class. + /// + /// The store of the settings persisted by the host, or when no store is available. + /// The unique identifier of the plugin whose settings are read. + /// The runtime settings with the default values and the optional configuration callback already applied. + public LocalMusicArtworkSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, LocalMusicArtworkSettingsDto defaults) + { + _settingsStore = settingsStore; + _pluginId = pluginId; + _defaults = defaults; + } + + /// + /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call. + /// + /// Cancellation token that can be used to stop the execution. + /// The runtime settings of the plugin. + public async Task GetAsync(CancellationToken cancellationToken) + { + // Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact. + LocalMusicArtworkSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is not null) + return runtimeSettings; + + // Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once. + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // Second check inside the gate: another caller may have resolved the settings while this one was waiting for it. + runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is null) + { + // The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes. + runtimeSettings = new LocalMusicArtworkSettingsDto + { + ShouldExtractEmbeddedCover = _defaults.ShouldExtractEmbeddedCover + }; + + if (_settingsStore is not null) + { + IReadOnlyDictionary? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false); + if (storedSettings is not null && + storedSettings.TryGetValue(LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER, out string? shouldExtractEmbeddedCover) && + bool.TryParse(shouldExtractEmbeddedCover, out bool shouldExtractEmbeddedCoverValue)) + runtimeSettings.ShouldExtractEmbeddedCover = shouldExtractEmbeddedCoverValue; + } + + // Publishing through Volatile makes the fully built instance visible to the lock free readers above. + Volatile.Write(ref _runtimeSettings, runtimeSettings); + } + + return runtimeSettings; + } + finally + { + _gate.Release(); + } + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Lumina.Plugins.LocalMusicArtwork.csproj b/plugins/Lumina.Plugins.LocalMusicArtwork/Lumina.Plugins.LocalMusicArtwork.csproj new file mode 100644 index 00000000..406f5b96 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Lumina.Plugins.LocalMusicArtwork.csproj @@ -0,0 +1,38 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + + + + + + + + + + + + + + false + runtime + + + + + + + + + + + diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..f0b1cda2 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.SecurityTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.IntegrationTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.Fixtures")] diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs new file mode 100644 index 00000000..f4364382 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +using System.Net.Http; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the MusicBrainz metadata provider into the Dependency Injection container. +/// +internal static class MusicBrainzServices +{ + /// + /// Registers the services of the MusicBrainz metadata providers into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the metadata. + /// Action used to configure the . + /// The updated . + internal static IServiceCollection AddMusicBrainzMetadataProviders(this IServiceCollection services, Guid pluginId, Action? settingsCallback = null) + { + ArgumentNullException.ThrowIfNull(services); + + // Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback. + services.TryAddScoped(serviceProvider => + { + MusicBrainzSettingsDto defaults = new(); + settingsCallback?.Invoke(defaults); + + IPluginSettingsStore? settingsStore = serviceProvider.GetService(); + return new MusicBrainzSettingsProvider(settingsStore, pluginId, defaults); + }); + + // The throttle must be process-wide, because the MusicBrainz web service enforces its request policy across all callers, not per scope. + services.TryAddSingleton(); + + // The response cache is process-wide, so that an entity shared by many items, like a release shared by all its tracks, is fetched only once. + services.TryAddSingleton(); + + // Redirects are not followed, so the configurable base URL cannot be used to reach an internal address through a redirect from a mirror. + services.AddHttpClient() + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); + + // Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations. + // A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair. + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs new file mode 100644 index 00000000..80aa0157 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an alias of a MusicBrainz entity. +/// +internal sealed record MusicBrainzAliasResponse +{ + /// + /// Gets the name of the alias. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the sort name of the alias. + /// + [JsonPropertyName("sort-name")] + public string? SortName { get; init; } + + /// + /// Gets the type of the alias. + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the locale the alias is used in. + /// + [JsonPropertyName("locale")] + public string? Locale { get; init; } + + /// + /// Gets a value indicating whether this is the primary alias. + /// + [JsonPropertyName("primary")] + public bool? IsPrimary { get; init; } + + /// + /// Gets the begin date of the alias. + /// + [JsonPropertyName("begin")] + public string? Begin { get; init; } + + /// + /// Gets the end date of the alias. + /// + [JsonPropertyName("end")] + public string? End { get; init; } + + /// + /// Gets a value indicating whether the alias has ended. + /// + [JsonPropertyName("ended")] + public bool? IsEnded { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs new file mode 100644 index 00000000..1049e58a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an area from the MusicBrainz API. +/// +internal sealed record MusicBrainzAreaResponse +{ + /// + /// Gets the MusicBrainz identifier of the area. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the name of the area. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the sort name of the area. + /// + [JsonPropertyName("sort-name")] + public string? SortName { get; init; } + + /// + /// Gets the disambiguation comment of the area. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the MusicBrainz type of the area. + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the ISO 3166-1 codes of the area. + /// + [JsonPropertyName("iso-3166-1-codes")] + public List Iso3166Part1Codes { get; init; } = []; + + /// + /// Gets the ISO 3166-2 codes of the area. + /// + [JsonPropertyName("iso-3166-2-codes")] + public List Iso3166Part2Codes { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs new file mode 100644 index 00000000..b659ba13 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a single credit in the artist credit of a MusicBrainz entity. +/// +internal sealed record MusicBrainzArtistCreditResponse +{ + /// + /// Gets the credited name of the artist. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the join phrase that follows the credit. + /// + [JsonPropertyName("joinphrase")] + public string? JoinPhrase { get; init; } + + /// + /// Gets the artist the credit refers to. + /// + [JsonPropertyName("artist")] + public MusicBrainzArtistResponse? Artist { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs new file mode 100644 index 00000000..bfedacfd --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an artist from the MusicBrainz API. +/// +internal sealed record MusicBrainzArtistResponse +{ + /// + /// Gets the MusicBrainz identifier of the artist. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the name of the artist. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the sort name of the artist. + /// + [JsonPropertyName("sort-name")] + public string? SortName { get; init; } + + /// + /// Gets the disambiguation comment of the artist. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the MusicBrainz type of the artist. + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the gender of the artist. + /// + [JsonPropertyName("gender")] + public string? Gender { get; init; } + + /// + /// Gets the ISO 3166-1 alpha-2 code of the country of the artist. + /// + [JsonPropertyName("country")] + public string? Country { get; init; } + + /// + /// Gets the area the artist is primarily identified with. + /// + [JsonPropertyName("area")] + public MusicBrainzAreaResponse? Area { get; init; } + + /// + /// Gets the area the artist began in. + /// + [JsonPropertyName("begin-area")] + public MusicBrainzAreaResponse? BeginArea { get; init; } + + /// + /// Gets the area the artist ended in. + /// + [JsonPropertyName("end-area")] + public MusicBrainzAreaResponse? EndArea { get; init; } + + /// + /// Gets the life span of the artist. + /// + [JsonPropertyName("life-span")] + public MusicBrainzLifeSpanResponse? LifeSpan { get; init; } + + /// + /// Gets the ISNI codes of the artist. + /// + [JsonPropertyName("isnis")] + public List Isnis { get; init; } = []; + + /// + /// Gets the IPI codes of the artist. + /// + [JsonPropertyName("ipis")] + public List Ipis { get; init; } = []; + + /// + /// Gets the alternative names of the artist. + /// + [JsonPropertyName("aliases")] + public List Aliases { get; init; } = []; + + /// + /// Gets the tags of the artist. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the artist. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the relationships of the artist to other entities. + /// + [JsonPropertyName("relations")] + public List Relations { get; init; } = []; + + /// + /// Gets the aggregated rating of the artist. + /// + [JsonPropertyName("rating")] + public MusicBrainzRatingResponse? Rating { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs new file mode 100644 index 00000000..21abdaa3 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an artist search from the MusicBrainz API. +/// +internal sealed record MusicBrainzArtistSearchResponse +{ + /// + /// Gets the total number of matching artists. + /// + [JsonPropertyName("count")] + public int Count { get; init; } + + /// + /// Gets the offset of the returned artists. + /// + [JsonPropertyName("offset")] + public int Offset { get; init; } + + /// + /// Gets the matching artists. + /// + [JsonPropertyName("artists")] + public List Artists { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs new file mode 100644 index 00000000..3a45cd2a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the label information of a MusicBrainz release. +/// +internal sealed record MusicBrainzLabelInfoResponse +{ + /// + /// Gets the catalog number assigned by the label. + /// + [JsonPropertyName("catalog-number")] + public string? CatalogNumber { get; init; } + + /// + /// Gets the label that issued the release. + /// + [JsonPropertyName("label")] + public MusicBrainzLabelResponse? Label { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs new file mode 100644 index 00000000..2a9c49e8 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a label from the MusicBrainz API. +/// +internal sealed record MusicBrainzLabelResponse +{ + /// + /// Gets the MusicBrainz identifier of the label. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the name of the label. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the disambiguation comment of the label. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the label code of the label. + /// + [JsonPropertyName("label-code")] + public int? LabelCode { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs new file mode 100644 index 00000000..1a8ef2c5 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the life span of a MusicBrainz artist, label, or area. +/// +internal sealed record MusicBrainzLifeSpanResponse +{ + /// + /// Gets the begin date of the life span. + /// + [JsonPropertyName("begin")] + public string? Begin { get; init; } + + /// + /// Gets the end date of the life span. + /// + [JsonPropertyName("end")] + public string? End { get; init; } + + /// + /// Gets a value indicating whether the life span has ended. + /// + [JsonPropertyName("ended")] + public bool? IsEnded { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs new file mode 100644 index 00000000..e7e2f675 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a medium of a MusicBrainz release. +/// +internal sealed record MusicBrainzMediumResponse +{ + /// + /// Gets the position of the medium within its release. + /// + [JsonPropertyName("position")] + public int Position { get; init; } + + /// + /// Gets the title of the medium. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the format of the medium (e.g., CD, Vinyl, Digital Media). + /// + [JsonPropertyName("format")] + public string? Format { get; init; } + + /// + /// Gets the number of tracks of the medium. + /// + [JsonPropertyName("track-count")] + public int TrackCount { get; init; } + + /// + /// Gets the tracks of the medium. The tracks are only returned when the recordings are included in the request. + /// + [JsonPropertyName("tracks")] + public List Tracks { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs new file mode 100644 index 00000000..f0983b8a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the aggregated rating of a MusicBrainz entity. +/// +internal sealed record MusicBrainzRatingResponse +{ + /// + /// Gets the average rating value. + /// + [JsonPropertyName("value")] + public decimal? Value { get; init; } + + /// + /// Gets the number of votes that contributed to the rating. + /// + [JsonPropertyName("votes-count")] + public int? VotesCount { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs new file mode 100644 index 00000000..a1dbc913 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the recordings returned by an ISRC lookup from the MusicBrainz API. +/// +internal sealed record MusicBrainzRecordingListResponse +{ + /// + /// Gets the recordings that carry the looked up ISRC. + /// + [JsonPropertyName("recordings")] + public List Recordings { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs new file mode 100644 index 00000000..9b773f15 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a recording from the MusicBrainz API. +/// +internal sealed record MusicBrainzRecordingResponse +{ + /// + /// Gets the MusicBrainz identifier of the recording. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the title of the recording. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the disambiguation comment of the recording. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the length of the recording in milliseconds. + /// + [JsonPropertyName("length")] + public long? Length { get; init; } + + /// + /// Gets a value indicating whether the recording is a video recording. + /// + [JsonPropertyName("video")] + public bool? IsVideo { get; init; } + + /// + /// Gets the date the recording was first released. + /// + [JsonPropertyName("first-release-date")] + public string? FirstReleaseDate { get; init; } + + /// + /// Gets the artist credit of the recording. + /// + [JsonPropertyName("artist-credit")] + public List ArtistCredit { get; init; } = []; + + /// + /// Gets the ISRC (International Standard Recording Code) of the recording. + /// + [JsonPropertyName("isrcs")] + public List Isrcs { get; init; } = []; + + /// + /// Gets the releases the recording appears on. + /// + [JsonPropertyName("releases")] + public List Releases { get; init; } = []; + + /// + /// Gets the tags of the recording. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the recording. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the relationships of the recording to other entities (e.g., its work, and its performers). + /// + [JsonPropertyName("relations")] + public List Relations { get; init; } = []; + + /// + /// Gets the aggregated rating of the recording. + /// + [JsonPropertyName("rating")] + public MusicBrainzRatingResponse? Rating { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs new file mode 100644 index 00000000..6e9fe611 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a recording search from the MusicBrainz API. +/// +internal sealed record MusicBrainzRecordingSearchResponse +{ + /// + /// Gets the total number of matching recordings. + /// + [JsonPropertyName("count")] + public int Count { get; init; } + + /// + /// Gets the offset of the returned recordings. + /// + [JsonPropertyName("offset")] + public int Offset { get; init; } + + /// + /// Gets the matching recordings. + /// + [JsonPropertyName("recordings")] + public List Recordings { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs new file mode 100644 index 00000000..269fcc50 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a relationship between a MusicBrainz entity and another entity. +/// +internal sealed record MusicBrainzRelationResponse +{ + /// + /// Gets the type of the relationship (e.g., producer, composer, member of band). + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the MusicBrainz identifier of the type of the relationship. + /// + [JsonPropertyName("type-id")] + public string? TypeId { get; init; } + + /// + /// Gets the direction of the relationship. + /// + [JsonPropertyName("direction")] + public string? Direction { get; init; } + + /// + /// Gets the type of the entity the relationship targets. + /// + [JsonPropertyName("target-type")] + public string? TargetType { get; init; } + + /// + /// Gets the artist the relationship targets, when the target is an artist. + /// + [JsonPropertyName("artist")] + public MusicBrainzArtistResponse? Artist { get; init; } + + /// + /// Gets the work the relationship targets, when the target is a work. + /// + [JsonPropertyName("work")] + public MusicBrainzWorkResponse? Work { get; init; } + + /// + /// Gets the URL the relationship targets, when the target is a URL. + /// + [JsonPropertyName("url")] + public MusicBrainzUrlResponse? Url { get; init; } + + /// + /// Gets the attributes of the relationship (e.g., the instrument that was performed). + /// + [JsonPropertyName("attributes")] + public List Attributes { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs new file mode 100644 index 00000000..9735cb3a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the result of browsing the releases linked to another MusicBrainz entity. +/// +internal sealed record MusicBrainzReleaseBrowseResponse +{ + /// + /// Gets the releases returned by the browse request. + /// + [JsonPropertyName("releases")] + public List Releases { get; init; } = []; + + /// + /// Gets the total number of releases linked to the browsed entity. + /// + [JsonPropertyName("release-count")] + public int ReleaseCount { get; init; } + + /// + /// Gets the offset of the returned releases. + /// + [JsonPropertyName("release-offset")] + public int ReleaseOffset { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs new file mode 100644 index 00000000..fd4722c7 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a release event of a MusicBrainz release. +/// +internal sealed record MusicBrainzReleaseEventResponse +{ + /// + /// Gets the date of the release event. + /// + [JsonPropertyName("date")] + public string? Date { get; init; } + + /// + /// Gets the area of the release event. + /// + [JsonPropertyName("area")] + public MusicBrainzAreaResponse? Area { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs new file mode 100644 index 00000000..50e8e909 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a release group from the MusicBrainz API. +/// +internal sealed record MusicBrainzReleaseGroupResponse +{ + /// + /// Gets the MusicBrainz identifier of the release group. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the title of the release group. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the disambiguation comment of the release group. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the primary type of the release group. + /// + [JsonPropertyName("primary-type")] + public string? PrimaryType { get; init; } + + /// + /// Gets the secondary types of the release group. + /// + [JsonPropertyName("secondary-types")] + public List SecondaryTypes { get; init; } = []; + + /// + /// Gets the date the release group was first released. + /// + [JsonPropertyName("first-release-date")] + public string? FirstReleaseDate { get; init; } + + /// + /// Gets the artist credit of the release group. + /// + [JsonPropertyName("artist-credit")] + public List ArtistCredit { get; init; } = []; + + /// + /// Gets the releases of the release group. + /// + [JsonPropertyName("releases")] + public List Releases { get; init; } = []; + + /// + /// Gets the tags of the release group. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the release group. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the aggregated rating of the release group. + /// + [JsonPropertyName("rating")] + public MusicBrainzRatingResponse? Rating { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs new file mode 100644 index 00000000..eafa8cf9 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a release group search from the MusicBrainz API. +/// +internal sealed record MusicBrainzReleaseGroupSearchResponse +{ + /// + /// Gets the total number of matching release groups. + /// + [JsonPropertyName("count")] + public int Count { get; init; } + + /// + /// Gets the offset of the returned release groups. + /// + [JsonPropertyName("offset")] + public int Offset { get; init; } + + /// + /// Gets the matching release groups. + /// + [JsonPropertyName("release-groups")] + public List ReleaseGroups { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs new file mode 100644 index 00000000..529b7373 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a release from the MusicBrainz API. +/// +internal sealed record MusicBrainzReleaseResponse +{ + /// + /// Gets the MusicBrainz identifier of the release. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the title of the release. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the disambiguation comment of the release. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the status of the release (e.g., Official, Bootleg). + /// + [JsonPropertyName("status")] + public string? Status { get; init; } + + /// + /// Gets the date the release was issued. + /// + [JsonPropertyName("date")] + public string? Date { get; init; } + + /// + /// Gets the ISO 3166-1 alpha-2 code of the country the release was issued in. + /// + [JsonPropertyName("country")] + public string? Country { get; init; } + + /// + /// Gets the release events of the release. + /// + [JsonPropertyName("release-events")] + public List ReleaseEvents { get; init; } = []; + + /// + /// Gets the barcode of the release. + /// + [JsonPropertyName("barcode")] + public string? Barcode { get; init; } + + /// + /// Gets the outermost packaging of the release. + /// + [JsonPropertyName("packaging")] + public string? Packaging { get; init; } + + /// + /// Gets the language and script of the titles of the release. + /// + [JsonPropertyName("text-representation")] + public MusicBrainzTextRepresentationResponse? TextRepresentation { get; init; } + + /// + /// Gets the artist credit of the release. + /// + [JsonPropertyName("artist-credit")] + public List ArtistCredit { get; init; } = []; + + /// + /// Gets the release group the release belongs to. + /// + [JsonPropertyName("release-group")] + public MusicBrainzReleaseGroupResponse? ReleaseGroup { get; init; } + + /// + /// Gets the label information of the release. + /// + [JsonPropertyName("label-info")] + public List LabelInfo { get; init; } = []; + + /// + /// Gets the media of the release. + /// + [JsonPropertyName("media")] + public List Media { get; init; } = []; + + /// + /// Gets the ASIN (Amazon Standard Identification Number) of the release. + /// + [JsonPropertyName("asin")] + public string? Asin { get; init; } + + /// + /// Gets the tags of the release. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the release. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the relationships of the release to other entities (e.g., its producers and engineers). + /// + [JsonPropertyName("relations")] + public List Relations { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs new file mode 100644 index 00000000..a14387ba --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a tag or a genre of a MusicBrainz entity. +/// +internal sealed record MusicBrainzTagResponse +{ + /// + /// Gets the MusicBrainz identifier of the genre, when the tag is a genre. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the name of the tag. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the disambiguation comment of the genre, when the tag is a genre. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the number of votes the tag received. + /// + [JsonPropertyName("count")] + public int Count { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs new file mode 100644 index 00000000..ab04f364 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the language and script of the titles of a MusicBrainz release. +/// +internal sealed record MusicBrainzTextRepresentationResponse +{ + /// + /// Gets the ISO 639-3 language code of the release. + /// + [JsonPropertyName("language")] + public string? Language { get; init; } + + /// + /// Gets the ISO 15924 script code of the release. + /// + [JsonPropertyName("script")] + public string? Script { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs new file mode 100644 index 00000000..0015672f --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a track of a medium of a MusicBrainz release, including the recording it is a performance of. +/// +internal sealed record MusicBrainzTrackResponse +{ + /// + /// Gets the MusicBrainz identifier of the track. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the track number, as displayed on the medium (for example, "1" or "A1"). + /// + [JsonPropertyName("number")] + public string? Number { get; init; } + + /// + /// Gets the position of the track within its medium. + /// + [JsonPropertyName("position")] + public int Position { get; init; } + + /// + /// Gets the title of the track. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the length of the track in milliseconds. + /// + [JsonPropertyName("length")] + public long? Length { get; init; } + + /// + /// Gets the recording the track is a performance of. + /// + [JsonPropertyName("recording")] + public MusicBrainzRecordingResponse? Recording { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs new file mode 100644 index 00000000..f7d4e06c --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a URL from the MusicBrainz API. +/// +internal sealed record MusicBrainzUrlResponse +{ + /// + /// Gets the MusicBrainz identifier of the URL. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the resource the URL points to. + /// + [JsonPropertyName("resource")] + public string? Resource { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs new file mode 100644 index 00000000..09c43be2 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a work from the MusicBrainz API. +/// +internal sealed record MusicBrainzWorkResponse +{ + /// + /// Gets the MusicBrainz identifier of the work. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the title of the work. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the MusicBrainz type of the work. + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the disambiguation comment of the work. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the languages of the work. + /// + [JsonPropertyName("languages")] + public List Languages { get; init; } = []; + + /// + /// Gets the ISWC (International Standard Musical Work Code) of the work. + /// + [JsonPropertyName("iswcs")] + public List Iswcs { get; init; } = []; + + /// + /// Gets the relationships of the work to other entities (e.g., its composers and lyricists). + /// + [JsonPropertyName("relations")] + public List Relations { get; init; } = []; + + /// + /// Gets the tags of the work. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the work. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs new file mode 100644 index 00000000..2c97fbab --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; + +/// +/// Data transfer object for the settings that configure the MusicBrainz metadata plugin. +/// +internal sealed class MusicBrainzSettingsDto +{ + /// + /// Gets or sets the base URL of the MusicBrainz web service the requests are sent to. + /// Defaults to the public MusicBrainz web service, and can point to a self hosted mirror instead. + /// + public string BaseUrl { get; set; } = "https://musicbrainz.org/ws/2/"; + + /// + /// Gets or sets a value indicating whether the base URL is allowed to point at a private or local host, for a self hosted mirror on a local + /// network. Defaults to , so that a misconfigured base URL cannot silently reach a local service. + /// + public bool DoesAllowPrivateBaseUrl { get; set; } + + /// + /// Gets or sets the user agent sent with every request to the MusicBrainz API. + /// + public string UserAgent { get; set; } = "Lumina-MusicBrainz/1.0"; + + /// + /// Gets or sets the contact email sent with every request to the MusicBrainz API. + /// + public string? ContactEmail { get; set; } + + /// + /// Gets or sets the maximum number of results returned by a single search. + /// + public int SearchResultLimit { get; set; } = 10; + + /// + /// Gets or sets the maximum number of releases fetched for a single release group. + /// + public int ReleaseLookupLimit { get; set; } = 25; + + /// + /// Gets or sets the minimum interval between consecutive requests to the MusicBrainz API. + /// MusicBrainz requires client applications to make no more than one request per second. + /// + public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0); +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs new file mode 100644 index 00000000..70407049 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs @@ -0,0 +1,336 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Api; + +/// +/// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models. +/// +internal sealed class MusicBrainzHttpClient +{ + private readonly HttpClient _httpClient; + private readonly MusicBrainzSettingsProvider _settingsProvider; + private readonly MusicBrainzRequestThrottle _requestThrottle; + private readonly MusicBrainzResponseCache _responseCache; + + private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web) + { + NumberHandling = JsonNumberHandling.AllowReadingFromString + }; + + // Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich. + private const int MAXIMUM_ATTEMPT_COUNT = 4; + + /// + /// Initializes a new instance of the class. + /// + /// The used to send requests to the MusicBrainz web service. + /// The provider of the settings that configure the MusicBrainz web service requests. + /// The process-wide throttle that spaces out the requests sent to the MusicBrainz web service. + /// The process-wide cache that avoids fetching the same entity more than once during a run. + public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache) + { + _httpClient = httpClient; + _settingsProvider = settingsProvider; + _requestThrottle = requestThrottle; + _responseCache = responseCache; + } + + /// + /// Looks up the artist identified by . + /// + /// The MusicBrainz identifier of the artist. + /// Cancellation token that can be used to stop the execution. + /// The artist, or when no artist was found. + public Task GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken); + } + + /// + /// Searches MusicBrainz for artists matching the provided query. + /// + /// The search query. + /// The maximum number of results to return. + /// Cancellation token that can be used to stop the execution. + /// The list of matching artists. + public async Task> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken) + { + MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync( + $"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", + cancellationToken).ConfigureAwait(false); + return response?.Artists ?? []; + } + + /// + /// Looks up the release group identified by . + /// + /// The MusicBrainz identifier of the release group. + /// Cancellation token that can be used to stop the execution. + /// The release group, or when no release group was found. + public Task GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken); + } + + /// + /// Searches MusicBrainz for release groups matching the provided query. + /// + /// The search query. + /// The maximum number of results to return. + /// Cancellation token that can be used to stop the execution. + /// The list of matching release groups. + public async Task> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken) + { + MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync( + $"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", + cancellationToken).ConfigureAwait(false); + return response?.ReleaseGroups ?? []; + } + + /// + /// Looks up the release identified by . + /// + /// The MusicBrainz identifier of the release. + /// Cancellation token that can be used to stop the execution. + /// The release, or when no release was found. + public Task GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken); + } + + /// + /// Browses the releases that belong to the release group identified by . + /// + /// The MusicBrainz identifier of the release group. + /// The maximum number of releases to return. + /// Cancellation token that can be used to stop the execution. + /// The list of releases of the release group. + public async Task> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken) + { + MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync( + $"release?release-group={musicBrainzReleaseGroupId:D}&inc=artist-credits+labels+media&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", + cancellationToken).ConfigureAwait(false); + return response?.Releases ?? []; + } + + /// + /// Looks up the recording identified by . + /// + /// The MusicBrainz identifier of the recording. + /// Cancellation token that can be used to stop the execution. + /// The recording, or when no recording was found. + public Task GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken); + } + + /// + /// Searches MusicBrainz for recordings matching the provided query. + /// + /// The search query. + /// The maximum number of results to return. + /// Cancellation token that can be used to stop the execution. + /// The list of matching recordings. + public async Task> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken) + { + MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync( + $"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", + cancellationToken).ConfigureAwait(false); + return response?.Recordings ?? []; + } + + /// + /// Looks up the recordings that carry the provided ISRC. + /// + /// The ISRC to look up. + /// Cancellation token that can be used to stop the execution. + /// The list of recordings that carry the ISRC. + public async Task> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken) + { + MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync( + $"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false); + return response?.Recordings ?? []; + } + + /// + /// Looks up the work identified by , together with its credited contributors. + /// + /// The MusicBrainz identifier of the work. + /// Cancellation token that can be used to stop the execution. + /// The work, or when no work was found. + public Task GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken); + } + + /// + /// Looks up the release identified by , together with its media, tracks, recordings and all the data needed + /// to enrich those tracks, so that every track of the release is enriched from a single request. + /// + /// The MusicBrainz identifier of the release. + /// Cancellation token that can be used to stop the execution. + /// The release, with its media, tracks and recordings, or when no release was found. + public Task GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"release/{musicBrainzReleaseId:D}?inc=recordings+isrcs+artist-credits+tags+genres+ratings+work-rels+recording-level-rels+work-level-rels+artist-rels+release-groups+labels+media&fmt=json", cancellationToken); + } + + /// + /// Gets the JSON resource at the given relative URL and deserializes it into . + /// + /// The type to deserialize the JSON response into. + /// The URL of the resource, relative to the base address. + /// Cancellation token that can be used to stop the execution. + /// The deserialized resource, or when the resource was not found. + /// Transient failures and rate limiting are handled by retrying the request up to three times. + private async Task GetJsonOrNullAsync(string relativeUrl, CancellationToken cancellationToken) + { + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + string cacheKey = string.Concat(settings.BaseUrl, relativeUrl); + if (_responseCache.TryGet(cacheKey, out string? cachedJson) && cachedJson is not null) + return JsonSerializer.Deserialize(cachedJson, s_serializerOptions); + + using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false); + // A 404 means the entity does not exist in MusicBrainz, which is a normal miss rather than an error, so it is reported as no result. + if (response.StatusCode == HttpStatusCode.NotFound) + return default; + response.EnsureSuccessStatusCode(); + + string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + _responseCache.Set(cacheKey, json); + return JsonSerializer.Deserialize(json, s_serializerOptions); + } + + /// + /// Sends a GET request to the MusicBrainz web service, throttled to respect the configured minimum request interval unless the configured + /// base URL is not the real MusicBrainz service, in which case no rate limit is imposed. Transient failures, rate limiting and transport + /// exceptions are retried, preferring the delay requested by the web service when it is provided. + /// + /// The settings that configure the MusicBrainz web service requests. + /// The URL of the resource, relative to the base address. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message for the request. + private async Task SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken) + { + EnsureRequestHeaders(settings); + // The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted + // mirror, or any other configured base URL that is not the real service, is not limited by this process. + bool shouldThrottle = IsRealMusicBrainzService(settings.BaseUrl); + + // A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every + // attempt, so that the retries of a failed request cannot burst past the rate limit of the real MusicBrainz web service. + for (int attempt = 1; ; attempt++) + { + if (shouldThrottle) + await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false); + + bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT; + HttpResponseMessage response; + try + { + HttpRequestMessage request = new(HttpMethod.Get, BuildRequestUri(settings.BaseUrl, relativeUrl)); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + } + catch (HttpRequestException) when (!isLastAttempt) + { + await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false); + continue; + } + + if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500)) + { + TimeSpan retryDelay = GetRetryDelay(attempt, response); + // The response of a failed attempt is not returned, so it must be disposed here to release its connection. + response.Dispose(); + await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false); + continue; + } + + return response; + } + } + + /// + /// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided. + /// + /// The one based number of the attempt that just failed. + /// The response of the failed attempt, when the failure was a response rather than a transport exception. + /// The delay to wait before the next attempt. + private static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response) + { + if (response?.Headers.RetryAfter is { } retryAfter) + { + if (retryAfter.Delta is TimeSpan delta) + return delta; + if (retryAfter.Date is DateTimeOffset date) + { + TimeSpan wait = date - DateTimeOffset.UtcNow; + if (wait > TimeSpan.Zero) + return wait; + } + } + return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt)); + } + + /// + /// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed. + /// + /// The base URL of the MusicBrainz web service the requests are sent to. + /// when the base URL points to the real MusicBrainz web service, otherwise . + private static bool IsRealMusicBrainzService(string baseUrl) + { + if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out Uri? baseUri)) + return false; + return baseUri.Host.Equals("musicbrainz.org", StringComparison.OrdinalIgnoreCase) + || baseUri.Host.EndsWith(".musicbrainz.org", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set. + /// + /// The settings that configure the MusicBrainz web service requests. + private void EnsureRequestHeaders(MusicBrainzSettingsDto settings) + { + // The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once. + if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0) + { + string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail) + ? settings.UserAgent + : $"{settings.UserAgent} ( {settings.ContactEmail} )"; + _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent); + } + } + + /// + /// Combines the configured base URL with the given relative URL into the absolute URI of a request. + /// + /// The base URL of the MusicBrainz web service the requests are sent to. + /// The URL of the resource, relative to the base URL. + /// The absolute URI of the request. + private static Uri BuildRequestUri(string baseUrl, string relativeUrl) + { + string normalizedBaseUrl = baseUrl.EndsWith('/') ? baseUrl : string.Concat(baseUrl, "/"); + return new Uri(new Uri(normalizedBaseUrl, UriKind.Absolute), relativeUrl); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs new file mode 100644 index 00000000..43801c05 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Api; + +/// +/// Spaces out the requests sent to the MusicBrainz web service, so the configured minimum request interval is respected across every caller in the process. +/// +internal sealed class MusicBrainzRequestThrottle +{ + private readonly SemaphoreSlim _gate = new(1, 1); + + // The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter + // which caller sends them. + private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue; + + /// + /// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot. + /// + /// The minimum amount of time that must elapse between two consecutive requests. + /// Cancellation token that can be used to stop the execution. + /// A task that completes once the caller may send its request. + public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken) + { + // The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the + // previous reserved slot. + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it. + if (minimumRequestInterval > TimeSpan.Zero) + { + DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval; + TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow; + if (delay > TimeSpan.Zero) + await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + } + + _lastRequestAt = DateTimeOffset.UtcNow; + } + finally + { + _gate.Release(); + } + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs new file mode 100644 index 00000000..06b87f9c --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Api; + +/// +/// In-memory cache of the responses returned by the MusicBrainz web service, keyed by the requested URL. +/// It removes the repeated lookups of the same entity during a run, and expires its entries after a bounded time. +/// +internal sealed class MusicBrainzResponseCache +{ + /// + /// The maximum number of responses the cache keeps. + /// + internal const int MAXIMUM_ENTRY_COUNT = 20_000; + + /// + /// The maximum total number of characters of the cached response bodies. + /// + internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000; + + /// + /// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the + /// eviction from running on every write once a budget is reached. + /// + private const int TRIM_TARGET_PERCENT = 90; + + private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15); + + private readonly int _maximumEntryCount; + private readonly long _maximumCharacterCount; + private readonly TimeSpan _timeToLive; + private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); + + // The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction + // are guarded by a lock, while reads stay lock free. + private readonly Lock _sizeGate = new(); + private long _cachedCharacterCount; + + // Monotonically increasing insertion stamp, used to evict the oldest entries first. + private long _sequence; + + /// + /// Initializes a new instance of the class with the default budgets and time to live. + /// + public MusicBrainzResponseCache() + { + _maximumEntryCount = MAXIMUM_ENTRY_COUNT; + _maximumCharacterCount = MAXIMUM_CHARACTER_COUNT; + _timeToLive = s_timeToLive; + } + + /// + /// Initializes a new instance of the class with the provided budgets and time to live. + /// + /// The maximum number of responses the cache keeps. + /// The maximum total number of characters of the cached response bodies. + /// The amount of time a cached response stays valid. + internal MusicBrainzResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive) + { + _maximumEntryCount = maximumEntryCount; + _maximumCharacterCount = maximumCharacterCount; + _timeToLive = timeToLive; + } + + /// + /// Tries to get the cached response body for . + /// + /// The key of the cached response. + /// The cached response body, when found. + /// when an unexpired response was found, otherwise . + public bool TryGet(string key, out string? json) + { + // An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it. + if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow) + { + json = entry.Json; + return true; + } + json = null; + return false; + } + + /// + /// Adds or replaces the cached response body for , then trims the cache back to its budgets. + /// + /// The key of the cached response. + /// The response body to cache. + public void Set(string key, string json) + { + // A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache. + if (json.Length > _maximumCharacterCount) + return; + + lock (_sizeGate) + { + if (_entries.TryRemove(key, out CacheEntry? existing)) + _cachedCharacterCount -= existing.Json.Length; + + _entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence); + _cachedCharacterCount += json.Length; + + if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount) + TrimToBudget(); + } + } + + /// + /// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets. + /// + private void TrimToBudget() + { + DateTime utcNow = DateTime.UtcNow; + bool isOverEntryCount = _entries.Count > _maximumEntryCount; + bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount; + int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100); + long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100); + + // Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when + // a budget was not exceeded, so the cache keeps reclaiming dead entries. + foreach (KeyValuePair candidate in _entries.OrderBy(entry => entry.Value.Sequence)) + { + bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow; + bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget; + bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget; + if (!isExpired && !needsEntryTrim && !needsCharacterTrim) + break; + + if (_entries.TryRemove(candidate.Key, out CacheEntry? removed)) + _cachedCharacterCount -= removed.Json.Length; + } + } + + private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence); +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs new file mode 100644 index 00000000..5b6a363a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs @@ -0,0 +1,759 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Mapping; + +/// +/// Maps MusicBrainz web service responses into the application's media metadata DTOs. +/// +internal static partial class MusicBrainzMapper +{ + /// + /// The neutral cultures of the process, indexed by both their two letter and three letter ISO 639 codes. + /// Built once, because the available cultures do not change during the lifetime of the process. + /// + private static readonly IReadOnlyDictionary s_neutralCulturesByCode = BuildNeutralCultureLookup(); + + /// + /// Matches a four digit year. + /// + [GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")] + private static partial Regex YearPattern(); + + /// + /// Maps a MusicBrainz artist response into artist metadata. + /// + /// The artist response to map. + /// The mapped artist metadata. + public static ArtistMetadataDto MapArtist(MusicBrainzArtistResponse artist) + { + (List contributors, string? website) = MapArtistRelations(artist.Relations); + return new ArtistMetadataDto( + Name: NullIfWhiteSpace(artist.Name), + SortName: NullIfWhiteSpace(artist.SortName), + Disambiguation: NullIfWhiteSpace(artist.Disambiguation), + Type: MapArtistType(artist.Type), + Gender: MapArtistGender(artist.Gender), + Country: NullIfWhiteSpace(artist.Country), + Area: MapArea(artist.Area), + BeginArea: MapArea(artist.BeginArea), + EndArea: MapArea(artist.EndArea), + LifeSpanBegin: ParseDate(artist.LifeSpan?.Begin).Date, + LifeSpanEnd: ParseDate(artist.LifeSpan?.End).Date, + IsEnded: artist.LifeSpan?.IsEnded ?? false, + Website: website, + MusicBrainzArtistId: ParseGuid(artist.Id), + Ipis: [.. artist.Ipis.Where(ipi => !string.IsNullOrWhiteSpace(ipi))], + Isnis: [.. artist.Isnis.Where(isni => !string.IsNullOrWhiteSpace(isni))], + Aliases: [.. artist.Aliases.Select(MapAlias)], + Genres: MapGenres(artist.Genres), + Tags: MapTags(artist.Tags), + Ratings: MapRating(artist.Rating), + Contributors: contributors); + } + + /// + /// Maps a MusicBrainz release group, and optionally one of its releases, into album metadata. + /// + /// The release group response to map. + /// The selected release of the release group, or when no release was selected. + /// The mapped album metadata. + public static AlbumMetadataDto MapAlbum(MusicBrainzReleaseGroupResponse releaseGroup, MusicBrainzReleaseResponse? release) + { + (DateOnly? originalDate, int? originalYear) = ParseDate(releaseGroup.FirstReleaseDate); + (DateOnly? reReleaseDate, int? reReleaseYear) = ParseDate(release?.Date); + if (reReleaseDate is not null && originalDate is not null && reReleaseDate.Value.Year == originalDate.Value.Year) + { + reReleaseDate = null; + reReleaseYear = null; + } + + string? releaseArtistId = releaseGroup.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id)) + ?? release?.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id)); + + List contributors = MapArtistCredit(releaseGroup.ArtistCredit); + if (contributors.Count == 0 && release is not null) + contributors = MapArtistCredit(release.ArtistCredit); + if (release is not null) + AddContributors(contributors, MapContributorsFromRelations(release.Relations)); + + List media = release?.Media ?? []; + int totalTracks = media.Sum(medium => medium.TrackCount); + // A MusicBrainz release can carry several labels and catalog numbers: the label stores the first one, while every catalog number is kept. + string? label = release?.LabelInfo.FirstOrDefault()?.Label?.Name; + List catalogNumbers = [.. (release?.LabelInfo ?? []) + .Select(labelInfo => NullIfWhiteSpace(labelInfo.CatalogNumber)) + .Where(catalogNumber => catalogNumber is not null) + .Select(catalogNumber => catalogNumber!) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + + return new AlbumMetadataDto( + Title: NullIfWhiteSpace(releaseGroup.Title) ?? NullIfWhiteSpace(release?.Title), + OriginalTitle: null, + Description: null, + Disambiguation: NullIfWhiteSpace(releaseGroup.Disambiguation), + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: originalDate, + OriginalReleaseYear: originalYear, + ReReleaseDate: reReleaseDate, + ReReleaseYear: reReleaseYear, + ReleaseCountry: MapReleaseCountry(release?.Country), + ReleaseVersion: NullIfWhiteSpace(release?.Disambiguation)), + Language: MapLanguage(release?.TextRepresentation?.Language), + OriginalLanguage: null, + Tags: MapTags(releaseGroup.Tags), + Genres: MapGenres(releaseGroup.Genres), + Script: NullIfWhiteSpace(release?.TextRepresentation?.Script), + ReleaseTypes: MapReleaseTypes(releaseGroup.PrimaryType, releaseGroup.SecondaryTypes), + ReleaseStatus: MapReleaseStatus(release?.Status), + MediaFormat: MapMediaFormat(media.FirstOrDefault()?.Format), + Packaging: MapPackaging(release?.Packaging), + TotalDiscs: media.Count > 0 ? media.Count : null, + TotalTracks: totalTracks > 0 ? totalTracks : null, + Barcode: NullIfWhiteSpace(release?.Barcode), + CatalogNumbers: catalogNumbers, + Label: NullIfWhiteSpace(label), + ASIN: NullIfWhiteSpace(release?.Asin), + MusicBrainzReleaseId: ParseGuid(release?.Id), + MusicBrainzReleaseGroupId: ParseGuid(releaseGroup.Id), + MusicBrainzReleaseArtistId: ParseGuid(releaseArtistId), + Contributors: contributors, + Ratings: MapRating(releaseGroup.Rating), + ReleaseTitle: NullIfWhiteSpace(release?.Title)); + } + + /// + /// Maps a MusicBrainz recording, and optionally its work and release, into track metadata. + /// + /// The recording response to map. + /// The work the recording is an instance of, or when the recording has no work. + /// The release the recording appears on, or when it is not known. + /// The mapped track metadata. + public static AudioMetadataDto MapTrack(MusicBrainzRecordingResponse recording, MusicBrainzWorkResponse? work, MusicBrainzReleaseResponse? release) + { + (DateOnly? releaseDate, int? releaseYear) = ParseDate(recording.FirstReleaseDate); + // A recording embedded in a release lookup does not carry its own first release date, so the date of the release the track appears on is used + // instead, rather than leaving the track without any release date at all. + if (releaseYear is null) + (releaseDate, releaseYear) = ParseDate(release?.Date); + + List contributors = MapArtistCredit(recording.ArtistCredit); + AddContributors(contributors, MapContributorsFromRelations(recording.Relations)); + if (work is not null) + AddContributors(contributors, MapContributorsFromRelations(work.Relations)); + + return new AudioMetadataDto( + Title: NullIfWhiteSpace(recording.Title), + OriginalTitle: null, + Description: null, + Disambiguation: NullIfWhiteSpace(recording.Disambiguation), + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: releaseDate, + OriginalReleaseYear: releaseYear, + ReReleaseDate: null, + ReReleaseYear: null, + ReleaseCountry: null, + ReleaseVersion: null), + Language: MapLanguage(release?.TextRepresentation?.Language), + OriginalLanguage: null, + Tags: MapTags(recording.Tags), + Genres: MapGenres(recording.Genres), + Script: NullIfWhiteSpace(release?.TextRepresentation?.Script), + Key: null, + Bpm: null, + IsVideo: recording.IsVideo ?? false, + Work: work is null ? null : MapWork(work), + Isrcs: [.. recording.Isrcs.Where(isrc => !string.IsNullOrWhiteSpace(isrc)).Select(isrc => new IsrcDto(isrc))], + Moods: null, + DurationInSeconds: recording.Length is long length && length > 0 ? (int)(length / 1000) : null, + SampleRate: null, + Channels: null, + BitDepth: null, + AudioCodec: null, + Bitrate: null, + MusicBrainzRecordingId: ParseGuid(recording.Id), + MusicBrainzTrackId: null, + Contributors: contributors, + Ratings: MapRating(recording.Rating)); + } + + /// + /// Maps a MusicBrainz work into a work DTO. + /// + /// The work response to map. + /// The mapped work. + public static MusicWorkDto MapWork(MusicBrainzWorkResponse work) + { + return new MusicWorkDto( + MusicBrainzWorkId: ParseGuid(work.Id), + Title: NullIfWhiteSpace(work.Title), + Type: NullIfWhiteSpace(work.Type), + Languages: [.. work.Languages.Select(MapLanguage).Where(language => language is not null).Select(language => language!)], + Iswcs: [.. work.Iswcs.Where(iswc => !string.IsNullOrWhiteSpace(iswc))]); + } + + /// + /// Maps a MusicBrainz area into an area DTO. + /// + /// The area response to map. + /// The mapped area, or when no area is provided. + public static MusicAreaDto? MapArea(MusicBrainzAreaResponse? area) + { + if (area is null) + return null; + + string? isoCode = area.Iso3166Part1Codes.FirstOrDefault() ?? area.Iso3166Part2Codes.FirstOrDefault(); + return new MusicAreaDto( + MusicBrainzAreaId: ParseGuid(area.Id), + Name: NullIfWhiteSpace(area.Name), + SortName: NullIfWhiteSpace(area.SortName), + Disambiguation: NullIfWhiteSpace(area.Disambiguation), + Type: NullIfWhiteSpace(area.Type), + Iso3166Code: NullIfWhiteSpace(isoCode)); + } + + /// + /// Maps a MusicBrainz alias into an alias DTO. + /// + /// The alias response to map. + /// The mapped alias. + private static MusicArtistAliasDto MapAlias(MusicBrainzAliasResponse alias) + { + return new MusicArtistAliasDto( + Name: NullIfWhiteSpace(alias.Name), + SortName: NullIfWhiteSpace(alias.SortName), + Type: NullIfWhiteSpace(alias.Type), + Locale: NullIfWhiteSpace(alias.Locale), + IsPrimary: alias.IsPrimary ?? false, + BeginDate: ParseDate(alias.Begin).Date, + EndDate: ParseDate(alias.End).Date, + IsEnded: alias.IsEnded ?? false); + } + + /// + /// Maps the genres of a MusicBrainz entity into genre DTOs. + /// + /// The genre responses to map. + /// The mapped genre DTOs. + private static List MapGenres(IReadOnlyCollection genres) + { + return [.. genres + .Where(genre => !string.IsNullOrWhiteSpace(genre.Name)) + .Select(genre => new GenreDto(genre.Name)) + .DistinctBy(genre => genre.Name, StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Maps the tags of a MusicBrainz entity into tag DTOs. + /// + /// The tag responses to map. + /// The mapped tag DTOs. + private static List MapTags(IReadOnlyCollection tags) + { + return [.. tags + .Where(tag => !string.IsNullOrWhiteSpace(tag.Name)) + .Select(tag => new TagDto(tag.Name)) + .DistinctBy(tag => tag.Name, StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Maps the rating of a MusicBrainz entity into a rating DTO. + /// + /// The rating response to map. + /// The mapped rating DTO, or an empty list when no rating is provided. + private static List MapRating(MusicBrainzRatingResponse? rating) + { + if (rating is null || (rating.Value is null && rating.VotesCount is null)) + return []; + return [new AudioRatingDto(rating.Value, 5m, AudioRatingSource.MusicBrainz, rating.VotesCount)]; + } + + /// + /// Maps an ISO 639-3 language code into a language DTO. + /// + /// The code to map. + /// The mapped language, or when the code is empty. + private static LanguageInfoDto? MapLanguage(string? rawCode) + { + if (string.IsNullOrWhiteSpace(rawCode)) + return null; + + string code = rawCode.Trim().ToLowerInvariant(); + // A language code can list several languages, such as "eng/ara"; the first one is the language of the release. + string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code; + + // These ISO 639-3 codes describe a language absence rather than a culture, so they cannot be resolved through a culture. + switch (primaryCode) + { + case "zxx": + return new LanguageInfoDto(primaryCode, "No linguistic content", null); + case "mul": + return new LanguageInfoDto(primaryCode, "Multiple languages", null); + case "und": + return new LanguageInfoDto(primaryCode, "Undetermined", null); + default: + break; + } + + // Only neutral cultures are matched, because a specific culture would resolve to an arbitrary regional name such as "German (Austria)". + return s_neutralCulturesByCode.TryGetValue(primaryCode, out CultureInfo? culture) + ? new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName) + : new LanguageInfoDto(primaryCode, primaryCode, null); + } + + /// + /// Builds the lookup of the process' neutral cultures, indexed by both their two letter and three letter ISO 639 codes. + /// + /// The neutral cultures, indexed by their ISO 639 codes. + private static IReadOnlyDictionary BuildNeutralCultureLookup() + { + Dictionary culturesByCode = new(StringComparer.OrdinalIgnoreCase); + foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) + { + // A culture without a two letter ISO 639 code is not a language, so it is skipped; the two letter code is the one carried by the DTOs. + if (culture.TwoLetterISOLanguageName.Length != 2) + continue; + culturesByCode.TryAdd(culture.ThreeLetterISOLanguageName, culture); + culturesByCode.TryAdd(culture.TwoLetterISOLanguageName, culture); + } + return culturesByCode; + } + + /// + /// Maps the artist credit of a MusicBrainz entity into attributed performing contributors. + /// + /// The artist credit to map. + /// The mapped contributors. + private static List MapArtistCredit(IReadOnlyCollection artistCredit) + { + List contributors = []; + foreach (MusicBrainzArtistCreditResponse credit in artistCredit) + { + string? name = NullIfWhiteSpace(credit.Name) ?? NullIfWhiteSpace(credit.Artist?.Name); + if (name is null) + continue; + AddContributor(contributors, name, MediaContributorRole.Performer); + } + return contributors; + } + + /// + /// Maps the artist relations of a MusicBrainz entity into contributors, excluding the URL relations. + /// + /// The relations to map. + /// The mapped contributors. + private static List MapContributorsFromRelations(IReadOnlyCollection relations) + { + List contributors = []; + foreach (MusicBrainzRelationResponse relation in relations) + { + if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase)) + continue; + + string? name = NullIfWhiteSpace(relation.Artist?.Name); + if (name is null) + continue; + AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes)); + } + return contributors; + } + + /// + /// Maps the relations of an artist into its contributing members, and its official homepage. + /// + /// The relations of the artist. + /// The mapped contributors, and the official homepage of the artist. + private static (List Contributors, string? Website) MapArtistRelations(IReadOnlyCollection relations) + { + List contributors = []; + string? website = null; + foreach (MusicBrainzRelationResponse relation in relations) + { + if (string.Equals(relation.TargetType, "url", StringComparison.OrdinalIgnoreCase)) + { + if (website is null && string.Equals(relation.Type, "official homepage", StringComparison.OrdinalIgnoreCase)) + website = NullIfWhiteSpace(relation.Url?.Resource); + continue; + } + + if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase)) + continue; + + string? name = NullIfWhiteSpace(relation.Artist?.Name); + if (name is null) + continue; + AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes)); + } + return (contributors, website); + } + + /// + /// Adds a contributor to the provided list, unless an identical name and role pair is already present. + /// + /// The contributors collected so far. + /// The display name of the contributor. + /// The role the contributor played. + private static void AddContributor(List contributors, string displayName, MediaContributorRole role) + { + if (contributors.Any(contributor => + string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) && + contributor.Role == role)) + return; + contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName, null), role)); + } + + /// + /// Adds the contributors to , skipping the duplicate name and role pairs. + /// + /// The contributors collected so far. + /// The contributors to add. + private static void AddContributors(List contributors, IReadOnlyCollection incoming) + { + foreach (MediaContributorDto contributor in incoming) + { + if (contributor.Name?.DisplayName is not string displayName) + continue; + AddContributor(contributors, displayName, contributor.Role ?? MediaContributorRole.Other); + } + } + + /// + /// Maps a MusicBrainz relationship type, and its attributes, into a canonical media contributor role. + /// + /// The relationship type to map. + /// The attributes of the relationship. + /// The mapped contributor role. + private static MediaContributorRole MapRole(string? relationType, IReadOnlyCollection attributes) + { + // An instrument attribute is more specific than the generic relationship type, so it is preferred. + foreach (string attribute in attributes) + { + MediaContributorRole? attributed = MapInstrument(attribute); + if (attributed is not null) + return attributed.Value; + } + + if (string.IsNullOrWhiteSpace(relationType)) + return MediaContributorRole.Other; + + string type = relationType.Trim().ToLowerInvariant(); + if (type.Contains("executive producer", StringComparison.Ordinal)) + return MediaContributorRole.ExecutiveProducer; + if (type.Contains("producer", StringComparison.Ordinal)) + return MediaContributorRole.Producer; + if (type.Contains("remixer", StringComparison.Ordinal)) + return MediaContributorRole.Remixer; + if (type.Contains("mix", StringComparison.Ordinal)) + return MediaContributorRole.Mixer; + if (type.Contains("engineer", StringComparison.Ordinal) || type.Contains("mastering", StringComparison.Ordinal)) + return MediaContributorRole.Engineer; + if (type.Contains("composer", StringComparison.Ordinal)) + return MediaContributorRole.Composer; + if (type.Contains("writer", StringComparison.Ordinal)) + return MediaContributorRole.Author; + if (type.Contains("lyricist", StringComparison.Ordinal)) + return MediaContributorRole.Lyricist; + if (type.Contains("librettist", StringComparison.Ordinal)) + return MediaContributorRole.Lyricist; + if (type.Contains("arranger", StringComparison.Ordinal)) + return MediaContributorRole.Arranger; + if (type.Contains("conductor", StringComparison.Ordinal)) + return MediaContributorRole.Conductor; + if (type.Contains("orchestrator", StringComparison.Ordinal)) + return MediaContributorRole.Orchestrator; + if (type.Contains("backing vocals", StringComparison.Ordinal)) + return MediaContributorRole.BackingVocals; + if (type.Contains("vocal", StringComparison.Ordinal)) + return MediaContributorRole.Vocals; + if (type.Contains("member of band", StringComparison.Ordinal) || type.Contains("performer", StringComparison.Ordinal) || type.Contains("orchestra", StringComparison.Ordinal) || type.Contains("choir", StringComparison.Ordinal)) + return MediaContributorRole.Performer; + return MediaContributorRole.Other; + } + + /// + /// Maps a MusicBrainz instrument attribute into a canonical media contributor role. + /// + /// The instrument attribute to map. + /// The mapped contributor role, or when the attribute is not an instrument. + private static MediaContributorRole? MapInstrument(string? attribute) + { + if (string.IsNullOrWhiteSpace(attribute)) + return null; + + string value = attribute.Trim().ToLowerInvariant(); + if (value.Contains("backing vocal", StringComparison.Ordinal)) + return MediaContributorRole.BackingVocals; + if (value.Contains("vocal", StringComparison.Ordinal)) + return MediaContributorRole.Vocals; + if (value.Contains("bass guitar", StringComparison.Ordinal)) + return MediaContributorRole.BassGuitar; + if (value.Contains("guitar", StringComparison.Ordinal)) + return MediaContributorRole.Guitar; + if (value.Contains("drum", StringComparison.Ordinal)) + return MediaContributorRole.Drums; + if (value.Contains("percussion", StringComparison.Ordinal)) + return MediaContributorRole.Percussion; + if (value.Contains("keyboard", StringComparison.Ordinal)) + return MediaContributorRole.Keyboards; + if (value.Contains("piano", StringComparison.Ordinal)) + return MediaContributorRole.Piano; + if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal)) + return MediaContributorRole.Synthesizer; + if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal)) + return MediaContributorRole.Strings; + if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal)) + return MediaContributorRole.Brass; + if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal)) + return MediaContributorRole.Woodwinds; + return null; + } + + /// + /// Maps a MusicBrainz artist type into the application enum. + /// + /// The artist type to map. + /// The mapped artist type, or when the type is unknown. + private static MusicArtistType? MapArtistType(string? type) + { + if (string.IsNullOrWhiteSpace(type)) + return null; + return type.Trim().ToLowerInvariant() switch + { + "person" => MusicArtistType.Person, + "group" => MusicArtistType.Group, + "orchestra" => MusicArtistType.Orchestra, + "choir" => MusicArtistType.Choir, + "character" => MusicArtistType.Character, + "other" => MusicArtistType.Other, + _ => null + }; + } + + /// + /// Maps a MusicBrainz gender into the application enum. + /// + /// The gender to map. + /// The mapped gender, or when the gender is unknown. + private static MusicArtistGender? MapArtistGender(string? gender) + { + if (string.IsNullOrWhiteSpace(gender)) + return null; + return gender.Trim().ToLowerInvariant() switch + { + "male" => MusicArtistGender.Male, + "female" => MusicArtistGender.Female, + "other" => MusicArtistGender.Other, + "not applicable" => MusicArtistGender.NotApplicable, + _ => null + }; + } + + /// + /// Maps the primary and secondary types of a release group into the application enum. + /// + /// The primary type of the release group. + /// The secondary types of the release group. + /// The mapped release types. + private static List MapReleaseTypes(string? primaryType, IReadOnlyCollection secondaryTypes) + { + List releaseTypes = []; + MusicReleaseType? primary = MapReleaseType(primaryType); + if (primary is not null) + releaseTypes.Add(primary.Value); + + foreach (string secondaryType in secondaryTypes) + { + MusicReleaseType? mapped = MapReleaseType(secondaryType); + if (mapped is not null && !releaseTypes.Contains(mapped.Value)) + releaseTypes.Add(mapped.Value); + } + return releaseTypes; + } + + /// + /// Maps a single MusicBrainz release type into the application enum. + /// + /// The release type to map. + /// The mapped release type, or when the type is unknown. + private static MusicReleaseType? MapReleaseType(string? type) + { + if (string.IsNullOrWhiteSpace(type)) + return null; + return type.Trim().ToLowerInvariant() switch + { + "album" => MusicReleaseType.Album, + "single" => MusicReleaseType.Single, + "ep" => MusicReleaseType.Ep, + "broadcast" => MusicReleaseType.Broadcast, + "other" => MusicReleaseType.Other, + "compilation" => MusicReleaseType.Compilation, + "live" => MusicReleaseType.Live, + "soundtrack" => MusicReleaseType.Soundtrack, + "spokenword" => MusicReleaseType.SpokenWord, + "audio drama" => MusicReleaseType.AudioDrama, + "audiobook" => MusicReleaseType.AudioBook, + "demo" => MusicReleaseType.Demo, + "dj-mix" => MusicReleaseType.DjMix, + "field recording" => MusicReleaseType.FieldRecording, + "interview" => MusicReleaseType.Interview, + "mixtape/street" => MusicReleaseType.Mixtape, + "remix" => MusicReleaseType.Remix, + _ => null + }; + } + + /// + /// Maps a MusicBrainz release status into the application enum. + /// + /// The release status to map. + /// The mapped release status, or when the status is unknown. + private static MusicReleaseStatus? MapReleaseStatus(string? status) + { + if (string.IsNullOrWhiteSpace(status)) + return null; + return status.Trim().ToLowerInvariant() switch + { + "official" => MusicReleaseStatus.Official, + "promotion" => MusicReleaseStatus.Promotion, + "bootleg" => MusicReleaseStatus.Bootleg, + "pseudo-release" => MusicReleaseStatus.PseudoRelease, + "withdrawn" => MusicReleaseStatus.Withdrawn, + "cancelled" => MusicReleaseStatus.Cancelled, + "expunged" => MusicReleaseStatus.Expunged, + _ => null + }; + } + + /// + /// Maps a MusicBrainz medium format into the application enum. + /// + /// The format to map. + /// The mapped media format, or when the format is unknown. + private static MusicMediaFormat? MapMediaFormat(string? format) + { + if (string.IsNullOrWhiteSpace(format)) + return null; + return format.Trim().ToLowerInvariant() switch + { + "cd" => MusicMediaFormat.CD, + "vinyl" => MusicMediaFormat.Vinyl, + "12\" vinyl" => MusicMediaFormat.Inch12Vinyl, + "10\" vinyl" => MusicMediaFormat.Inch10Vinyl, + "7\" vinyl" => MusicMediaFormat.Inch7Vinyl, + "digital media" => MusicMediaFormat.DigitalMedia, + "cassette" => MusicMediaFormat.Cassette, + "dvd" => MusicMediaFormat.DVD, + "dvd-video" => MusicMediaFormat.DVDVideo, + "dvd-audio" => MusicMediaFormat.DVDAudio, + "sacd" => MusicMediaFormat.SACD, + "hybrid sacd" => MusicMediaFormat.HybridSACD, + "blu-ray" => MusicMediaFormat.BluRay, + "minidisc" => MusicMediaFormat.MiniDisc, + "8cm cd" => MusicMediaFormat.Cm8CD, + "dat" => MusicMediaFormat.DAT, + "other" => MusicMediaFormat.Other, + _ => MusicMediaFormat.Other + }; + } + + /// + /// Maps a MusicBrainz release packaging into the application enum. + /// + /// The packaging to map. + /// The mapped packaging, or when the packaging is unknown. + private static MusicReleasePackaging? MapPackaging(string? packaging) + { + if (string.IsNullOrWhiteSpace(packaging)) + return null; + return packaging.Trim().ToLowerInvariant() switch + { + "book" => MusicReleasePackaging.Book, + "box" => MusicReleasePackaging.Box, + "cardboard/paper sleeve" => MusicReleasePackaging.CardboardPaperSleeve, + "cassette case" => MusicReleasePackaging.CassetteCase, + "clamshell case" => MusicReleasePackaging.ClamshellCase, + "digibook" => MusicReleasePackaging.Digibook, + "digifile" => MusicReleasePackaging.Digifile, + "digipak" => MusicReleasePackaging.Digipak, + "discbox slider" => MusicReleasePackaging.DiscboxSlider, + "fatbox" => MusicReleasePackaging.Fatbox, + "gatefold cover" => MusicReleasePackaging.GatefoldCover, + "jewel case" => MusicReleasePackaging.JewelCase, + "keep case" => MusicReleasePackaging.KeepCase, + "longbox" => MusicReleasePackaging.Longbox, + "metal tin" => MusicReleasePackaging.MetalTin, + "plastic sleeve" => MusicReleasePackaging.PlasticSleeve, + "slidepack" => MusicReleasePackaging.Slidepack, + "slim jewel case" => MusicReleasePackaging.SlimJewelCase, + "slipcase" => MusicReleasePackaging.Slipcase, + "snap case" => MusicReleasePackaging.SnapCase, + "snappack" => MusicReleasePackaging.SnapPack, + "super jewel box" => MusicReleasePackaging.SuperJewelBox, + "none" => MusicReleasePackaging.None, + "other" => MusicReleasePackaging.Other, + _ => MusicReleasePackaging.Other + }; + } + + /// + /// Maps an ISO 3166-1 alpha-2 country code into the application enum. + /// + /// The country code to map. + /// The mapped release country, or when the code is unknown. + private static ReleaseCountry? MapReleaseCountry(string? country) + { + if (string.IsNullOrWhiteSpace(country)) + return null; + return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null; + } + + /// + /// Parses a MusicBrainz identifier into a . + /// + /// The MusicBrainz identifier to parse. + /// The parsed identifier, or when the value is not a valid identifier. + private static Guid? ParseGuid(string? value) + { + return Guid.TryParse(value, out Guid parsed) ? parsed : null; + } + + /// + /// Parses a MusicBrainz date string into a date and a year. + /// + /// The date string to parse. + /// The parsed date and year, or values when the string could not be parsed. + private static (DateOnly? Date, int? Year) ParseDate(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return (null, null); + + if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact)) + return (exact, exact.Year); + + Match yearMatch = YearPattern().Match(value); + return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null); + } + + /// + /// Returns the trimmed value, or when the value is empty or white space. + /// + /// The value to process. + /// The trimmed value, or . + private static string? NullIfWhiteSpace(string? value) + { + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs new file mode 100644 index 00000000..ccdef688 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs @@ -0,0 +1,206 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Mapping; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core; + +/// +/// Provides album metadata from MusicBrainz by resolving lookups into album metadata DTOs. +/// A MusicBrainz release group is the logical album, while one of its releases is selected as the edition the local files match. +/// +internal sealed class MusicBrainzAlbumMetadataProvider : IMetadataProvider +{ + private readonly MusicBrainzHttpClient _musicBrainzHttpClient; + private readonly MusicBrainzSettingsProvider _settingsProvider; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "MusicBrainz"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => true; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP client used to call the MusicBrainz web service. + /// The provider of the settings that configure the MusicBrainz web service requests. + public MusicBrainzAlbumMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider) + { + _musicBrainzHttpClient = musicBrainzHttpClient; + _settingsProvider = settingsProvider; + } + + /// + /// Searches for the metadata of the album described by . + /// + /// The lookup describing the album to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of album metadata candidates found. + public async Task> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(lookup.Title)) + return []; + + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + IReadOnlyList releaseGroups = await _musicBrainzHttpClient + .SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false); + + List candidates = []; + foreach (MusicBrainzReleaseGroupResponse releaseGroup in releaseGroups) + if (!string.IsNullOrWhiteSpace(releaseGroup.Title)) + candidates.Add(MusicBrainzMapper.MapAlbum(releaseGroup, null)); + + return candidates; + } + + /// + /// Gets the metadata of the album described by . + /// + /// The lookup describing the album to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the album, or when no album was found. + public async Task GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + MusicBrainzReleaseResponse? release = null; + MusicBrainzReleaseGroupResponse? releaseGroup = null; + + // A release identifier pins the exact edition, so it is fetched first, and its release group is then resolved for the album level fields. + // The release is fetched together with its recordings, so that the track level enrichment of the same release is served from the response cache. + if (lookup.MusicBrainzReleaseId is not null) + release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false); + + Guid? releaseGroupId = lookup.MusicBrainzReleaseGroupId; + if (releaseGroupId is null && release?.ReleaseGroup?.Id is string releaseGroupIdValue && Guid.TryParse(releaseGroupIdValue, out Guid parsedReleaseGroupId)) + releaseGroupId = parsedReleaseGroupId; + + if (releaseGroupId is not null) + releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(releaseGroupId.Value, cancellationToken).ConfigureAwait(false); + + // Without any identifier, the album is searched by title and artist, and the first match is resolved in full. + if (release is null && releaseGroup is null && !string.IsNullOrWhiteSpace(lookup.Title)) + { + IReadOnlyList results = await _musicBrainzHttpClient + .SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), 1, cancellationToken).ConfigureAwait(false); + MusicBrainzReleaseGroupResponse? searchResult = results.Count > 0 ? results[0] : null; + if (searchResult?.Id is string searchResultId && Guid.TryParse(searchResultId, out Guid parsedSearchResultId)) + releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(parsedSearchResultId, cancellationToken).ConfigureAwait(false); + } + + if (releaseGroup is null) + return release is null ? null : MusicBrainzMapper.MapAlbum(new MusicBrainzReleaseGroupResponse { Id = release.ReleaseGroup?.Id, Title = release.Title }, release); + + // When the exact release was not pinned by the lookup, the best edition of the release group is selected. + if (release is null && releaseGroup.Id is string releaseGroupIdentifier && Guid.TryParse(releaseGroupIdentifier, out Guid releaseGroupGuid)) + { + IReadOnlyList releases = await _musicBrainzHttpClient + .BrowseReleasesByReleaseGroupAsync(releaseGroupGuid, settings.ReleaseLookupLimit, cancellationToken).ConfigureAwait(false); + release = SelectRelease(releases, lookup); + } + + return MusicBrainzMapper.MapAlbum(releaseGroup, release); + } + + /// + /// Selects the release of a release group that best matches the lookup, favoring official releases and those released in the lookup year. + /// + /// The releases to select from. + /// The lookup the selected release must match. + /// The best matching release, or when no release was provided. + private static MusicBrainzReleaseResponse? SelectRelease(IReadOnlyList releases, AlbumMetadataLookupDto lookup) + { + // Only a release whose tracklist matches the local album is selected, so that an edition of the release group that does not correspond to the + // local files is never attached to the album; without a known local track count, no release can be confidently matched, so none is selected. + if (lookup.TrackCount is not int trackCount) + return null; + + List matchingReleases = [.. releases.Where(release => release.Media.Sum(medium => medium.TrackCount) == trackCount)]; + if (matchingReleases.Count == 0) + return null; + + return matchingReleases + .Select((release, index) => new + { + Release = release, + Index = index, + Score = ScoreRelease(release, lookup) + }) + .OrderByDescending(item => item.Score) + .ThenBy(item => item.Index) + .Select(item => item.Release) + .First(); + } + + /// + /// Scores a release against the lookup to rank how well it matches. + /// + /// The release to score. + /// The lookup the release must match. + /// The match score of the release, where a higher score is a better match. + private static int ScoreRelease(MusicBrainzReleaseResponse release, AlbumMetadataLookupDto lookup) + { + int score = 0; + if (string.Equals(release.Status, "Official", StringComparison.OrdinalIgnoreCase)) + score += 10_000; + + if (lookup.ReleaseYear is int wantedYear && TryGetYear(release.Date) is int releaseYear && releaseYear == wantedYear) + score += 1_000; + + if (!string.IsNullOrWhiteSpace(release.Barcode)) + score += 100; + if (release.LabelInfo.Count > 0) + score += 50; + if (release.Media.Count > 0) + score += 10; + return score; + } + + /// + /// Gets the year of a MusicBrainz date string. + /// + /// The date string to read. + /// The year of the date, or when it could not be read. + private static int? TryGetYear(string? date) + { + if (string.IsNullOrWhiteSpace(date)) + return null; + string year = date.Length >= 4 ? date[..4] : date; + return int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? parsed : null; + } + + /// + /// Builds the MusicBrainz release group search query for the provided title and artist. + /// + /// The title of the release group. + /// The name of the artist, if applicable. + /// The built search query. + private static string BuildReleaseGroupQuery(string title, string? artistName) + { + string query = $"releasegroup:\"{title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""; + if (!string.IsNullOrWhiteSpace(artistName)) + query += $" AND artist:\"{artistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""; + return query; + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs new file mode 100644 index 00000000..30ef2ff9 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Mapping; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core; + +/// +/// Provides music artist metadata from MusicBrainz by resolving lookups into artist metadata DTOs. +/// +internal sealed class MusicBrainzArtistMetadataProvider : IMetadataProvider +{ + private readonly MusicBrainzHttpClient _musicBrainzHttpClient; + private readonly MusicBrainzSettingsProvider _settingsProvider; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "MusicBrainz"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => true; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP client used to call the MusicBrainz web service. + /// The provider of the settings that configure the MusicBrainz web service requests. + public MusicBrainzArtistMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider) + { + _musicBrainzHttpClient = musicBrainzHttpClient; + _settingsProvider = settingsProvider; + } + + /// + /// Searches for the metadata of the artist described by . + /// + /// The lookup describing the artist to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of artist metadata candidates found. + public async Task> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(lookup.Name)) + return []; + + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + IReadOnlyList artists = await _musicBrainzHttpClient + .SearchArtistsAsync(lookup.Name.Trim(), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false); + + List candidates = []; + foreach (MusicBrainzArtistResponse artist in artists) + if (!string.IsNullOrWhiteSpace(artist.Name)) + candidates.Add(MusicBrainzMapper.MapArtist(artist)); + return candidates; + } + + /// + /// Gets the metadata of the artist described by . + /// + /// The lookup describing the artist to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the artist, or when no artist was found. + public async Task GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + // A MusicBrainz identifier is the most precise lookup, so it is used first, if present. + if (lookup.MusicBrainzArtistId is not null) + { + MusicBrainzArtistResponse? artist = await _musicBrainzHttpClient.GetArtistAsync(lookup.MusicBrainzArtistId.Value, cancellationToken).ConfigureAwait(false); + return artist is null ? null : MusicBrainzMapper.MapArtist(artist); + } + + if (string.IsNullOrWhiteSpace(lookup.Name)) + return null; + + // Without an identifier, the artist is searched by name, and the first match is resolved in full. + IReadOnlyList artists = await _musicBrainzHttpClient + .SearchArtistsAsync(lookup.Name.Trim(), 1, cancellationToken).ConfigureAwait(false); + MusicBrainzArtistResponse? searchResult = artists.Count > 0 ? artists[0] : null; + if (searchResult?.Id is null) + return null; + + MusicBrainzArtistResponse? detailedArtist = System.Guid.TryParse(searchResult.Id, out System.Guid artistId) + ? await _musicBrainzHttpClient.GetArtistAsync(artistId, cancellationToken).ConfigureAwait(false) + : null; + return detailedArtist is null ? MusicBrainzMapper.MapArtist(searchResult) : MusicBrainzMapper.MapArtist(detailedArtist); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs new file mode 100644 index 00000000..e582c0d9 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.MusicBrainz.Common.DependencyInjection; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core; + +/// +/// Plugin that provides music metadata retrieval from MusicBrainz. +/// +public sealed class MusicBrainzPlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "MusicBrainz Metadata"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Retrieves artist, album and track metadata from MusicBrainz."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return + [ + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.BASE_URL, + Label: "Base URL", + Type: PluginSettingType.Text, + DefaultValue: "https://musicbrainz.org/ws/2/"), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, + Label: "Allow LAN/Private Base URL", + Type: PluginSettingType.Boolean, + DefaultValue: "false"), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.CONTACT_EMAIL, + Label: "Contact Email", + Type: PluginSettingType.Text), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, + Label: "Search Result Limit", + Type: PluginSettingType.Number, + DefaultValue: "10"), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, + Label: "Release Lookup Limit", + Type: PluginSettingType.Number, + DefaultValue: "25"), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, + Label: "Minimum Request Interval (seconds)", + Type: PluginSettingType.Number, + DefaultValue: "1.0") + ]; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddMusicBrainzMetadataProviders(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs new file mode 100644 index 00000000..25a0c763 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs @@ -0,0 +1,270 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Mapping; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core; + +/// +/// Provides track metadata from MusicBrainz by resolving lookups into audio metadata DTOs. +/// +internal sealed class MusicBrainzTrackMetadataProvider : IMetadataProvider +{ + private readonly MusicBrainzHttpClient _musicBrainzHttpClient; + private readonly MusicBrainzSettingsProvider _settingsProvider; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "MusicBrainz"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => true; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP client used to call the MusicBrainz web service. + /// The provider of the settings that configure the MusicBrainz web service requests. + public MusicBrainzTrackMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider) + { + _musicBrainzHttpClient = musicBrainzHttpClient; + _settingsProvider = settingsProvider; + } + + /// + /// Searches for the metadata of the track described by . + /// + /// The lookup describing the track to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of track metadata candidates found. + public async Task> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(lookup.Title)) + return []; + + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + IReadOnlyList recordings = await _musicBrainzHttpClient + .SearchRecordingsAsync(BuildRecordingQuery(lookup), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false); + + List candidates = []; + foreach (MusicBrainzRecordingResponse recording in recordings) + if (!string.IsNullOrWhiteSpace(recording.Title)) + candidates.Add(MusicBrainzMapper.MapTrack(recording, null, null)); + return candidates; + } + + /// + /// Gets the metadata of the track described by . + /// + /// The lookup describing the track to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the track, or when no track was found. + public async Task GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + // When the release the track belongs to is known, the release is fetched once, with all its recordings, and the track is resolved from its + // tracklist; the recording of that response already carries its work, so every track of the release is enriched from a single request. + if (lookup.MusicBrainzReleaseId is not null) + { + MusicBrainzReleaseResponse? release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false); + MusicBrainzTrackResponse? releaseTrack = release is null ? null : FindTrack(release, lookup); + if (releaseTrack?.Recording is not null) + { + MusicBrainzWorkResponse? inlineWork = await ResolveFallbackWorkAsync(ResolveInlineWork(releaseTrack.Recording), lookup, cancellationToken).ConfigureAwait(false); + return MusicBrainzMapper.MapTrack(releaseTrack.Recording, inlineWork, release); + } + } + + MusicBrainzRecordingResponse? recording = null; + + // A recording identifier is the most precise lookup, so it is used next, if present. + if (lookup.MusicBrainzRecordingId is not null) + recording = await _musicBrainzHttpClient.GetRecordingAsync(lookup.MusicBrainzRecordingId.Value, cancellationToken).ConfigureAwait(false); + + // An ISRC lookup returns the recordings that carry the code, the first of which is then resolved in full. + if (recording is null && !string.IsNullOrWhiteSpace(lookup.Isrc)) + { + IReadOnlyList recordings = await _musicBrainzHttpClient + .GetRecordingsByIsrcAsync(lookup.Isrc.Trim(), cancellationToken).ConfigureAwait(false); + MusicBrainzRecordingResponse? match = recordings.FirstOrDefault(); + recording = await ResolveRecordingAsync(match, cancellationToken).ConfigureAwait(false); + } + + // Without an identifier or a code, the track is searched, and the first match is resolved in full. + if (recording is null && !string.IsNullOrWhiteSpace(lookup.Title)) + { + IReadOnlyList recordings = await _musicBrainzHttpClient + .SearchRecordingsAsync(BuildRecordingQuery(lookup), 1, cancellationToken).ConfigureAwait(false); + recording = await ResolveRecordingAsync(recordings.FirstOrDefault(), cancellationToken).ConfigureAwait(false); + } + + if (recording is null) + return null; + + MusicBrainzWorkResponse? work = await ResolveWorkAsync(recording, cancellationToken).ConfigureAwait(false); + work = await ResolveFallbackWorkAsync(work, lookup, cancellationToken).ConfigureAwait(false); + MusicBrainzReleaseResponse? resolvedRelease = await ResolveReleaseAsync(recording, cancellationToken).ConfigureAwait(false); + return MusicBrainzMapper.MapTrack(recording, work, resolvedRelease); + } + + /// + /// Falls back to the work identifier of the tags when MusicBrainz did not link the recording to a work. + /// + /// The work resolved from MusicBrainz, if any. + /// The lookup describing the local track. + /// Cancellation token that can be used to stop the execution. + /// The provided work, the work resolved from the work identifier of the tags, or when neither is available. + private async Task ResolveFallbackWorkAsync(MusicBrainzWorkResponse? work, TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + // The title of the tags means the work of the tags is already complete, so it is kept as is and MusicBrainz is not queried again for it. + if (work is not null || lookup.MusicBrainzWorkId is not Guid musicBrainzWorkId || !string.IsNullOrWhiteSpace(lookup.WorkTitle)) + return work; + return await _musicBrainzHttpClient.GetWorkAsync(musicBrainzWorkId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Finds the track of that matches the provided , matching the recording identifier first, + /// then the disc and track numbers, then the title, and finally the duration. + /// + /// The release whose tracklist is searched. + /// The lookup describing the local track. + /// The matching track, or when no track matched. + private static MusicBrainzTrackResponse? FindTrack(MusicBrainzReleaseResponse release, TrackMetadataLookupDto lookup) + { + // The recording identifier is the most precise match, so it is used first, if present. + if (lookup.MusicBrainzRecordingId is Guid musicBrainzRecordingId) + { + foreach (MusicBrainzMediumResponse medium in release.Media) + foreach (MusicBrainzTrackResponse track in medium.Tracks) + if (track.Recording?.Id is string recordingId && Guid.TryParse(recordingId, out Guid trackRecordingId) && trackRecordingId == musicBrainzRecordingId) + return track; + } + + List candidates = []; + foreach (MusicBrainzMediumResponse medium in release.Media) + { + if (lookup.DiscNumber is int discNumber && medium.Position != discNumber) + continue; + foreach (MusicBrainzTrackResponse track in medium.Tracks) + { + if (lookup.TrackNumber is int trackNumber && track.Position != trackNumber) + continue; + candidates.Add(track); + } + } + if (candidates.Count <= 1) + return candidates.Count == 1 ? candidates[0] : null; + + // The disc and track numbers were not enough to single the track out, so the title is used next, and the duration breaks any remaining tie. + if (!string.IsNullOrWhiteSpace(lookup.Title)) + { + List titledCandidates = [.. candidates.Where(candidate => string.Equals(candidate.Title, lookup.Title, StringComparison.OrdinalIgnoreCase))]; + if (titledCandidates.Count == 1) + return titledCandidates[0]; + if (titledCandidates.Count > 1) + candidates = titledCandidates; + } + if (candidates.Count > 1 && lookup.DurationInSeconds is int duration) + return candidates.OrderBy(candidate => Math.Abs((candidate.Length ?? 0) / 1000 - duration)).First(); + return candidates[0]; + } + + /// + /// Gets the work the provided is a performance of, from the relations already embedded in the response. + /// + /// The recording whose work is resolved. + /// The embedded work, or when the recording has no work. + private static MusicBrainzWorkResponse? ResolveInlineWork(MusicBrainzRecordingResponse recording) + { + return recording.Relations + .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase)) + .Select(relation => relation.Work) + .FirstOrDefault(work => work is not null); + } + + /// + /// Resolves the full recording of the provided search or ISRC lookup result. + /// + /// The partial recording to resolve. + /// Cancellation token that can be used to stop the execution. + /// The full recording, or when the recording could not be resolved. + private async Task ResolveRecordingAsync(MusicBrainzRecordingResponse? recording, CancellationToken cancellationToken) + { + if (recording?.Id is null || !Guid.TryParse(recording.Id, out Guid recordingId)) + return recording; + + return await _musicBrainzHttpClient.GetRecordingAsync(recordingId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the work the provided recording is an instance of, together with its credited contributors. + /// + /// The recording whose work is resolved. + /// Cancellation token that can be used to stop the execution. + /// The work of the recording, or when the recording has no work. + private async Task ResolveWorkAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken) + { + string? workId = recording.Relations + .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase)) + .Select(relation => relation.Work?.Id) + .FirstOrDefault(id => !string.IsNullOrWhiteSpace(id)); + + if (workId is null || !Guid.TryParse(workId, out Guid parsedWorkId)) + return recording.Relations + .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase)) + .Select(relation => relation.Work) + .FirstOrDefault(work => work is not null); + + return await _musicBrainzHttpClient.GetWorkAsync(parsedWorkId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the release the provided recording appears on, for the release level language and script. + /// + /// The recording whose release is resolved. + /// Cancellation token that can be used to stop the execution. + /// The release of the recording, or when the recording does not reference a release. + private async Task ResolveReleaseAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken) + { + string? releaseId = recording.Releases.Select(release => release.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id)); + if (releaseId is null || !Guid.TryParse(releaseId, out Guid parsedReleaseId)) + return null; + + return await _musicBrainzHttpClient.GetReleaseAsync(parsedReleaseId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Builds the MusicBrainz recording search query for the provided lookup. + /// + /// The lookup describing the track. + /// The built search query. + private static string BuildRecordingQuery(TrackMetadataLookupDto lookup) + { + List parts = []; + if (!string.IsNullOrWhiteSpace(lookup.Title)) + parts.Add($"recording:\"{lookup.Title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""); + if (!string.IsNullOrWhiteSpace(lookup.ArtistName)) + parts.Add($"artist:\"{lookup.ArtistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""); + if (!string.IsNullOrWhiteSpace(lookup.ReleaseName)) + parts.Add($"release:\"{lookup.ReleaseName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""); + return string.Join(" AND ", parts); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs new file mode 100644 index 00000000..2ddd79e1 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs @@ -0,0 +1,37 @@ +namespace Lumina.Plugins.MusicBrainz.Core.Settings; + +/// +/// Keys of the settings of the MusicBrainz metadata plugin, shared by the settings schema and the settings loader. +/// +internal static class MusicBrainzSettingsKeys +{ + /// + /// The key of the setting defining the base URL of the MusicBrainz web service. + /// + internal const string BASE_URL = "BaseUrl"; + + /// + /// The key of the setting that allows the base URL to point at a private or local host, for a self hosted mirror on a local network. + /// + internal const string DOES_ALLOW_PRIVATE_BASE_URL = "DoesAllowPrivateBaseUrl"; + + /// + /// The key of the setting defining the contact email sent to the MusicBrainz API. + /// + internal const string CONTACT_EMAIL = "ContactEmail"; + + /// + /// The key of the setting defining the maximum number of results returned by a single search. + /// + internal const string SEARCH_RESULT_LIMIT = "SearchResultLimit"; + + /// + /// The key of the setting defining the maximum number of releases fetched for a single release group. + /// + internal const string RELEASE_LOOKUP_LIMIT = "ReleaseLookupLimit"; + + /// + /// The key of the setting defining the minimum interval between consecutive requests to the MusicBrainz API, in seconds. + /// + internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds"; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs new file mode 100644 index 00000000..5a667f17 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs @@ -0,0 +1,217 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Settings; + +/// +/// Provides the runtime settings of the MusicBrainz metadata plugin, overlaying the settings persisted by the host over the configured defaults. +/// +internal sealed class MusicBrainzSettingsProvider +{ + // The minimum request interval is clamped to a sane range, so a persisted value can neither be a non finite value that cannot be turned into a + // duration, nor be so large that waiting for it overflows the delay of the requests. + private const double MAXIMUM_REQUEST_INTERVAL_SECONDS = 60; + + private readonly IPluginSettingsStore? _settingsStore; + private readonly Guid _pluginId; + private readonly MusicBrainzSettingsDto _defaults; + + // The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already + // resolved path lock free; the gate is only needed by the first callers that race to resolve it. + private readonly SemaphoreSlim _gate = new(1, 1); + private MusicBrainzSettingsDto? _runtimeSettings; + + /// + /// Initializes a new instance of the class. + /// + /// The store of the settings persisted by the host, or when no store is available. + /// The unique identifier of the plugin whose settings are read. + /// The runtime settings with the default values and the optional configuration callback already applied. + public MusicBrainzSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, MusicBrainzSettingsDto defaults) + { + _settingsStore = settingsStore; + _pluginId = pluginId; + _defaults = defaults; + } + + /// + /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call. + /// + /// Cancellation token that can be used to stop the execution. + /// The runtime settings of the plugin. + public async Task GetAsync(CancellationToken cancellationToken) + { + // Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact. + MusicBrainzSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is not null) + return runtimeSettings; + + // Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once. + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // Second check inside the gate: another caller may have resolved the settings while this one was waiting for it. + runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is null) + { + // The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes. + runtimeSettings = Clone(_defaults); + if (_settingsStore is not null) + { + IReadOnlyDictionary? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false); + if (storedSettings is not null) + Apply(runtimeSettings, storedSettings); + } + + // Publishing through Volatile makes the fully built instance visible to the lock free readers above. + Volatile.Write(ref _runtimeSettings, runtimeSettings); + } + + return runtimeSettings; + } + finally + { + _gate.Release(); + } + } + + /// + /// Overlays the persisted settings onto the provided runtime settings, keeping the default values of the settings that were not persisted. + /// + /// The runtime settings onto which the persisted settings are applied. + /// The settings persisted by the host, keyed by setting key. + private static void Apply(MusicBrainzSettingsDto settings, IReadOnlyDictionary storedSettings) + { + // The private host opt-in must be resolved first, because it governs whether a private base URL is accepted below. + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, out string? doesAllowPrivateBaseUrl) && + bool.TryParse(doesAllowPrivateBaseUrl, out bool doesAllowPrivateBaseUrlValue)) + settings.DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrlValue; + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.BASE_URL, out string? baseUrl) && + Uri.TryCreate(baseUrl?.Trim(), UriKind.Absolute, out Uri? parsedBaseUrl) && + (parsedBaseUrl.Scheme == Uri.UriSchemeHttp || parsedBaseUrl.Scheme == Uri.UriSchemeHttps) && + (settings.DoesAllowPrivateBaseUrl || IsPublicHost(parsedBaseUrl.Host))) + settings.BaseUrl = parsedBaseUrl.AbsoluteUri; + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.CONTACT_EMAIL, out string? contactEmail)) + { + string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim(); + settings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null; + } + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, out string? searchResultLimit) && + int.TryParse(searchResultLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int searchResultLimitValue)) + settings.SearchResultLimit = Math.Max(1, searchResultLimitValue); + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, out string? releaseLookupLimit) && + int.TryParse(releaseLookupLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int releaseLookupLimitValue)) + settings.ReleaseLookupLimit = Math.Max(1, releaseLookupLimitValue); + + // A persisted value that is not a finite number is rejected, and a finite one is clamped, so that neither a NaN, nor an infinity, nor an + // out of range value can make the conversion to a duration or the waiting for it throw. + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) && + double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue) && + double.IsFinite(minimumRequestIntervalValue)) + settings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Clamp(minimumRequestIntervalValue, 0, MAXIMUM_REQUEST_INTERVAL_SECONDS)); + } + + /// + /// Determines whether the host of the persisted base URL is a public host, so the setting cannot be used to reach a local or private service. + /// + /// The host of the persisted base URL. + /// when the host is public, otherwise . + /// + /// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. + /// A private or local host is accepted when is enabled, which supports self hosted + /// mirrors on a local network. + /// + private static bool IsPublicHost(string host) + { + if (string.IsNullOrWhiteSpace(host)) + return false; + + // Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept. + string normalizedHost = host.Trim('[', ']'); + if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase)) + return false; + + if (!IPAddress.TryParse(normalizedHost, out IPAddress? address)) + return true; + + if (address.IsIPv4MappedToIPv6) + address = address.MapToIPv4(); + + if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) + return false; + + if (address.AddressFamily == AddressFamily.InterNetwork) + { + byte[] octets = address.GetAddressBytes(); + // The unspecified, private, loopback, link local and carrier grade NAT ranges are rejected, as they are the common targets of an SSRF. + return octets[0] switch + { + 0 => false, + 10 => false, + 100 when octets[1] is >= 64 and <= 127 => false, + 127 => false, + 169 when octets[1] == 254 => false, + 172 when octets[1] is >= 16 and <= 31 => false, + 192 when octets[1] == 168 => false, + _ => true + }; + } + + if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal) + return false; + + byte[] addressBytes = address.GetAddressBytes(); + // The fc00::/7 unique local range is rejected, matching the private IPv4 ranges. + if ((addressBytes[0] & 0xFE) == 0xFC) + return false; + + return true; + } + + /// + /// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header. + /// + /// The persisted contact email. + /// when the email is safe, otherwise . + private static bool IsSafeContactEmail(string contactEmail) + { + // The email is embedded in the User-Agent header, and an invalid character there throws when the header is parsed, which would break every request of the plugin, + // so anything outside a conservative email charset is rejected. + foreach (char character in contactEmail) + if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+')) + return false; + return true; + } + + /// + /// Creates a copy of the given runtime settings. + /// + /// The runtime settings to copy. + /// A copy of the given runtime settings. + private static MusicBrainzSettingsDto Clone(MusicBrainzSettingsDto source) + { + return new MusicBrainzSettingsDto + { + BaseUrl = source.BaseUrl, + DoesAllowPrivateBaseUrl = source.DoesAllowPrivateBaseUrl, + UserAgent = source.UserAgent, + ContactEmail = source.ContactEmail, + SearchResultLimit = source.SearchResultLimit, + ReleaseLookupLimit = source.ReleaseLookupLimit, + MinimumRequestInterval = source.MinimumRequestInterval + }; + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj b/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj new file mode 100644 index 00000000..bed7d79c --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj @@ -0,0 +1,34 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + + + + + + + + + + + + + + false + runtime + + + + + + + diff --git a/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..63a9ac3b --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.SecurityTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.Fixtures")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsLoader.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsLoader.cs index 772ed05e..98364c88 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsLoader.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsLoader.cs @@ -20,7 +20,10 @@ internal static class OpenLibrarySettingsLoader public static void Apply(OpenLibrarySettingsDto settings, IReadOnlyDictionary storedSettings) { if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.CONTACT_EMAIL, out string? contactEmail)) - settings.ContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim(); + { + string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim(); + settings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null; + } if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT, out string? searchResultLimit) && int.TryParse(searchResultLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int searchResultLimitValue)) @@ -34,4 +37,17 @@ internal static class OpenLibrarySettingsLoader double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue)) settings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Max(0, minimumRequestIntervalValue)); } + + /// + /// Determines whether the persisted contact email only contains characters that are safe inside the request from header. + /// + /// The persisted contact email. + /// when the email is safe, otherwise . + private static bool IsSafeContactEmail(string contactEmail) + { + foreach (char character in contactEmail) + if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+')) + return false; + return true; + } } diff --git a/plugins/Lumina.Plugins.OpenLibrary/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.OpenLibrary/Properties/AssemblyInfo.cs index 8ae45f58..dc1ecc59 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Properties/AssemblyInfo.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Properties/AssemblyInfo.cs @@ -1,8 +1,5 @@ using System.Runtime.CompilerServices; -// Test-enabling declaration for the Open Library plugin assembly. -// Mirrors the InternalsVisibleTo pattern present in every other testable source project, -// so that the internal Open Library types can be exercised by their unit tests. [assembly: InternalsVisibleTo("Lumina.Plugins.OpenLibrary.UnitTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.OpenLibrary.Fixtures")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryPathTemplatePartDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryPathTemplatePartDto.cs new file mode 100644 index 00000000..05a0898f --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryPathTemplatePartDto.cs @@ -0,0 +1,13 @@ +namespace Lumina.Application.Common.DTO.MediaLibrary.Management; + +/// +/// Data transfer object for one part of the path template of a media library, carried by the commands that create or update a media library. +/// +/// The kind of the path part. +/// The literal text or the value mask of the path part. +/// Whether the path part can be absent from the path. +public record LibraryPathTemplatePartDto( + string? Kind, + string? Representation, + bool IsOptional +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumCatalogNumberEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumCatalogNumberEntity.cs new file mode 100644 index 00000000..76234755 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumCatalogNumberEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for a catalog number of a music release. A release can carry more than one catalog number at the same time. +/// +/// The catalog number assigned by the label. +[DebuggerDisplay("CatalogNumber: {CatalogNumber}")] +public record AlbumCatalogNumberEntity( + string CatalogNumber +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs index 2a5c2330..c42bbf90 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -40,11 +41,21 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity /// public string? OriginalTitle { get; set; } + /// + /// Gets or sets the title of the specific release (edition) the album files match, if different from the release group title. + /// + public string? ReleaseTitle { get; set; } + /// /// Gets or sets the description of the album, if applicable. /// public string? Description { get; set; } + /// + /// Gets or sets the disambiguation comment of the album, used to distinguish albums with the same title, if applicable. + /// + public string? Disambiguation { get; set; } + /// /// Gets or sets the original release date of the album, if applicable. /// @@ -106,9 +117,9 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity public string? OriginalLanguageNativeName { get; set; } /// - /// Gets or sets the type of the release, if applicable. + /// Gets or sets the script used by the language of the release of the album, if applicable. /// - public MusicReleaseType? ReleaseType { get; set; } + public string? Script { get; set; } /// /// Gets or sets the status of the release, if applicable. @@ -130,15 +141,30 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity /// public MusicMediaFormat? MediaFormat { get; set; } + /// + /// Gets or sets the outermost physical packaging of the album, if applicable. + /// + public MusicReleasePackaging? Packaging { get; set; } + /// /// Gets or sets the barcode of the album, if applicable. /// public string? Barcode { get; set; } /// - /// Gets or sets the catalog number of the album, if applicable. + /// Gets or sets the catalog numbers of the album. /// - public string? CatalogNumber { get; set; } + public List CatalogNumbers { get; set; } = []; + + /// + /// Gets or sets the name of the label that issued the album, if applicable. + /// + public string? Label { get; set; } + + /// + /// Gets or sets the ASIN (Amazon Standard Identification Number) of the album, if applicable. + /// + public string? ASIN { get; set; } /// /// Gets or sets the MusicBrainz identifier of the release, if applicable. @@ -175,6 +201,11 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity /// public List Contributors { get; set; } = []; + /// + /// Gets or sets the types of the release. A release can carry more than one type at the same time. + /// + public List ReleaseTypes { get; set; } = []; + /// /// Gets or sets the genres of the album. /// @@ -185,6 +216,21 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity /// public HashSet Tags { get; set; } = []; + /// + /// Gets or sets the status of the metadata enrichment of the album. + /// + public MetadataStatus MetadataStatus { get; set; } + + /// + /// Gets or sets the date and time when the metadata of the album was last enriched. + /// + public DateTime? LastMetadataUpdateUtc { get; set; } + + /// + /// Gets or sets the name of the plugin that enriched the metadata of the album. + /// + public string? MetadataProvider { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumReleaseTypeEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumReleaseTypeEntity.cs new file mode 100644 index 00000000..c39cc489 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumReleaseTypeEntity.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for a type of a music release. A release can carry more than one type at the same time. +/// +/// The type of the release. +[DebuggerDisplay("ReleaseType: {ReleaseType}")] +public record AlbumReleaseTypeEntity( + MusicReleaseType ReleaseType +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistAliasEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistAliasEntity.cs new file mode 100644 index 00000000..c802fd6f --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistAliasEntity.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for an alternative name of a music artist. +/// +/// The name of the alias. +/// The sort name of the alias, if applicable. +/// The type of the alias, if applicable. +/// The locale the alias is used in, if applicable. +/// Whether this is the primary alias of the artist. +/// The date the alias began being used, if applicable. +/// The date the alias stopped being used, if applicable. +/// Whether the alias is no longer used. +[DebuggerDisplay("Name: {Name}")] +public record ArtistAliasEntity( + string Name, + string? SortName, + string? Type, + string? Locale, + bool IsPrimary, + DateOnly? BeginDate, + DateOnly? EndDate, + bool IsEnded +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs index 5a01a28b..380683c4 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -29,6 +30,46 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity /// public required string Name { get; set; } + /// + /// Gets or sets the sort name of the artist, a variant of the name used when sorting artists, if applicable. + /// + public string? SortName { get; set; } + + /// + /// Gets or sets the disambiguation comment of the artist, used to distinguish artists with the same name, if applicable. + /// + public string? Disambiguation { get; set; } + + /// + /// Gets or sets the type of the artist, if applicable. + /// + public MusicArtistType? Type { get; set; } + + /// + /// Gets or sets the gender of the artist, applicable only to artists that are persons or characters, if applicable. + /// + public MusicArtistGender? Gender { get; set; } + + /// + /// Gets or sets the ISO 3166-1 alpha-2 code of the country the artist is associated with, if applicable. + /// + public string? Country { get; set; } + + /// + /// Gets or sets the date the artist started existing, if applicable. + /// + public DateOnly? LifeSpanBegin { get; set; } + + /// + /// Gets or sets the date the artist stopped existing, if applicable. + /// + public DateOnly? LifeSpanEnd { get; set; } + + /// + /// Gets or sets a value indicating whether the artist no longer exists. + /// + public bool IsEnded { get; set; } + /// /// Gets or sets the website of the artist, if applicable. /// @@ -39,6 +80,51 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity /// public Guid? MusicBrainzArtistId { get; set; } + /// + /// Gets or sets the area the artist is primarily identified with, if applicable. + /// + public MusicAreaEntity? Area { get; set; } + + /// + /// Gets or sets the area the artist began in, if applicable. + /// + public MusicAreaEntity? BeginArea { get; set; } + + /// + /// Gets or sets the area the artist ended in, if applicable. + /// + public MusicAreaEntity? EndArea { get; set; } + + /// + /// Gets or sets the list of alternative names of the artist. + /// + public List Aliases { get; set; } = []; + + /// + /// Gets or sets the list of IPI (Interested Party Information) codes of the artist. + /// + public List Ipis { get; set; } = []; + + /// + /// Gets or sets the list of ISNI (International Standard Name Identifier) codes of the artist. + /// + public List Isnis { get; set; } = []; + + /// + /// Gets or sets the genres of the artist. + /// + public HashSet Genres { get; set; } = []; + + /// + /// Gets or sets the tags of the artist. + /// + public HashSet Tags { get; set; } = []; + + /// + /// Gets or sets the list of ratings of the artist. + /// + public List Ratings { get; set; } = []; + /// /// Gets or sets the albums of the artist. /// @@ -49,6 +135,21 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity /// public List Contributors { get; set; } = []; + /// + /// Gets or sets the status of the metadata enrichment of the artist. + /// + public MetadataStatus MetadataStatus { get; set; } + + /// + /// Gets or sets the date and time when the metadata of the artist was last enriched. + /// + public DateTime? LastMetadataUpdateUtc { get; set; } + + /// + /// Gets or sets the name of the plugin that enriched the metadata of the artist. + /// + public string? MetadataProvider { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIpiEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIpiEntity.cs new file mode 100644 index 00000000..1b8644d6 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIpiEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for an IPI (Interested Party Information) code of a music artist. +/// +/// The value of the IPI code. +[DebuggerDisplay("Value: {Value}")] +public record ArtistIpiEntity( + string Value +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIsniEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIsniEntity.cs new file mode 100644 index 00000000..ff3d5d63 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIsniEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for an ISNI (International Standard Name Identifier) code of a music artist. +/// +/// The value of the ISNI code. +[DebuggerDisplay("Value: {Value}")] +public record ArtistIsniEntity( + string Value +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaEntity.cs new file mode 100644 index 00000000..4902bf67 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaEntity.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for a MusicBrainz area, the geographic area a music artist is associated with. +/// +/// The MusicBrainz identifier of the area. +/// The name of the area. +/// The sort name of the area, if applicable. +/// The disambiguation comment of the area, if applicable. +/// The MusicBrainz type of the area, if applicable. +/// The ISO 3166 code of the area, if applicable. +[DebuggerDisplay("Name: {Name}")] +public record MusicAreaEntity( + Guid MusicBrainzAreaId, + string Name, + string? SortName, + string? Disambiguation, + string? Type, + string? Iso3166Code +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs new file mode 100644 index 00000000..db880c8b --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for a piece of artwork of a music library item, like the cover of an album or the image of an artist. +/// +/// +/// A music library item can have multiple pieces of artwork of different types, and multiple instances of the same type +/// (like the front cover, the back cover and the booklet pages of an album), each tracked independently so that a change +/// of one artwork does not require the others to be re-fetched. +/// +[DebuggerDisplay("OwnerType: {OwnerType} OwnerId: {OwnerId} Type: {ArtworkType} Ordinal: {Ordinal}")] +public class MusicArtworkEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the artwork. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the type of the music library item that owns the artwork. + /// + public required MusicArtworkOwnerType OwnerType { get; set; } + + /// + /// Gets or sets the Id of the music library item that owns the artwork. + /// + public required Guid OwnerId { get; set; } + + /// + /// Gets or sets the type of the artwork. + /// + public required ArtworkType ArtworkType { get; set; } + + /// + /// Gets or sets the ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered. + /// + public required int Ordinal { get; set; } + + /// + /// Gets or sets the relative file name of the stored artwork, if the artwork has been resolved. + /// + public string? FileName { get; set; } + + /// + /// Gets or sets the content hash of the stored artwork, used to detect whether a re-resolved artwork differs from the stored one. + /// + public ulong ContentHash { get; set; } + + /// + /// Gets or sets the status of the artwork enrichment. + /// + public required ArtworkStatus Status { get; set; } + + /// + /// Gets or sets the name of the plugin that resolved the artwork, if applicable. + /// + public string? Provider { get; set; } + + /// + /// Gets or sets the date and time when the artwork was last resolved, if applicable. + /// + public DateTime? LastUpdateUtc { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs new file mode 100644 index 00000000..8b943070 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntity.cs @@ -0,0 +1,171 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for the metadata extracted from a discovered music file, staged during a scan, before the artists, albums and tracks are materialized from it. +/// +[DebuggerDisplay("Path: {Path}")] +public class MusicLibraryScanItemMetadataEntity : IStorageEntity +{ + /// + /// Gets the Id of the staged music metadata. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the media library scan that this staged music metadata belongs to. + /// + public required Guid LibraryScanId { get; init; } + + /// + /// Gets the Id of the media library that this staged music metadata belongs to. + /// + public required Guid LibraryId { get; init; } + + /// + /// Gets the file system path of the music file whose metadata was extracted. + /// + public required string Path { get; init; } + + /// + /// Gets the name of the artist, if applicable. + /// + public string? ArtistName { get; set; } + + /// + /// Gets the type of the release, if applicable. + /// + public MusicReleaseType? ReleaseType { get; set; } + + /// + /// Gets the release year, if applicable. + /// + public int? ReleaseYear { get; set; } + + /// + /// Gets the name of the release, if applicable. + /// + public string? ReleaseName { get; set; } + + /// + /// Gets the title of the track, if applicable. + /// + public string? TrackTitle { get; set; } + + /// + /// Gets the number of the track on its disc, if applicable. + /// + public int? TrackNumber { get; set; } + + /// + /// Gets the number of the disc the track belongs to, if applicable. + /// + public int? DiscNumber { get; set; } + + /// + /// Gets the duration of the audio in seconds. + /// + public int DurationInSeconds { get; set; } + + /// + /// Gets the sample rate of the audio in Hz. + /// + public int SampleRate { get; set; } + + /// + /// Gets the number of audio channels. + /// + public int Channels { get; set; } + + /// + /// Gets the bit depth of the audio, if applicable. + /// + public int? BitDepth { get; set; } + + /// + /// Gets the audio codec used, if applicable. + /// + public string? AudioCodec { get; set; } + + /// + /// Gets or sets the bitrate of the audio in kbps, if applicable. + /// + public int? Bitrate { get; set; } + + /// + /// Gets or sets the AcoustID fingerprint identifier of the audio file, if applicable. + /// + public string? AcoustId { get; set; } + + /// + /// Gets or sets the ReplayGain track gain in decibels, if applicable. + /// + public decimal? ReplayGainTrackGain { get; set; } + + /// + /// Gets or sets the ReplayGain track peak, if applicable. + /// + public decimal? ReplayGainTrackPeak { get; set; } + + /// + /// Gets or sets the ReplayGain album gain in decibels, if applicable. + /// + public decimal? ReplayGainAlbumGain { get; set; } + + /// + /// Gets or sets the ReplayGain album peak, if applicable. + /// + public decimal? ReplayGainAlbumPeak { get; set; } + + /// + /// Gets or sets the moods of the track, read from the tags of the file. + /// + public List Moods { get; set; } = []; + + /// + /// Gets the MusicBrainz identifier of the artist, read from the tags of the file, if applicable. + /// + public Guid? MusicBrainzArtistId { get; set; } + + /// + /// Gets the MusicBrainz identifier of the release artist, read from the tags of the file, if applicable. + /// + public Guid? MusicBrainzReleaseArtistId { get; set; } + + /// + /// Gets the MusicBrainz identifier of the release group, read from the tags of the file, if applicable. + /// + public Guid? MusicBrainzReleaseGroupId { get; set; } + + /// + /// Gets the MusicBrainz identifier of the release, read from the tags of the file, if applicable. + /// + public Guid? MusicBrainzReleaseId { get; set; } + + /// + /// Gets the MusicBrainz identifier of the recording, read from the tags of the file, if applicable. + /// + public Guid? MusicBrainzRecordingId { get; set; } + + /// + /// Gets the MusicBrainz identifier of the track, read from the tags of the file, if applicable. + /// + public Guid? MusicBrainzTrackId { get; set; } + + /// + /// Gets the MusicBrainz identifier of the work the track is a recording of, read from the tags of the file, if applicable. + /// + public Guid? MusicBrainzWorkId { get; set; } + + /// + /// Gets the title of the work the track is a recording of, read from the tags of the file, if applicable. + /// + public string? WorkTitle { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs index 8ea83524..23a2794e 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -50,6 +51,11 @@ public class TrackEntity : IStorageEntity, IAuditableEntity /// public string? Description { get; set; } + /// + /// Gets or sets the disambiguation comment of the track, used to distinguish tracks with the same title, if applicable. + /// + public string? Disambiguation { get; set; } + /// /// Gets or sets the original release date of the track, if applicable. /// @@ -140,6 +146,31 @@ public class TrackEntity : IStorageEntity, IAuditableEntity /// public int? Bitrate { get; set; } + /// + /// Gets or sets the AcoustID fingerprint identifier of the audio file, if applicable. + /// + public string? AcoustId { get; set; } + + /// + /// Gets or sets the ReplayGain track gain in decibels, if applicable. + /// + public decimal? ReplayGainTrackGain { get; set; } + + /// + /// Gets or sets the ReplayGain track peak, if applicable. + /// + public decimal? ReplayGainTrackPeak { get; set; } + + /// + /// Gets or sets the ReplayGain album gain in decibels, if applicable. + /// + public decimal? ReplayGainAlbumGain { get; set; } + + /// + /// Gets or sets the ReplayGain album peak, if applicable. + /// + public decimal? ReplayGainAlbumPeak { get; set; } + /// /// Gets or sets the number of the track on its disc. /// @@ -165,10 +196,20 @@ public class TrackEntity : IStorageEntity, IAuditableEntity /// public int? Bpm { get; set; } + /// + /// Gets or sets a value indicating whether the recording of the track is a video recording. + /// + public bool IsVideo { get; set; } + /// /// Gets or sets the title of the work the track is a recording of, if applicable. /// - public string? Work { get; set; } + public string? WorkTitle { get; set; } + + /// + /// Gets or sets the MusicBrainz type of the work the track is a recording of, if applicable. + /// + public string? WorkType { get; set; } /// /// Gets or sets the MusicBrainz identifier of the recording, if applicable. @@ -200,6 +241,16 @@ public class TrackEntity : IStorageEntity, IAuditableEntity /// public List Isrcs { get; set; } = []; + /// + /// Gets or sets the list of the languages of the work the track is a recording of. + /// + public List WorkLanguages { get; set; } = []; + + /// + /// Gets or sets the list of ISWC (International Standard Musical Work Code) of the work the track is a recording of. + /// + public List WorkIswcs { get; set; } = []; + /// /// Gets or sets the list of the media contributors of the track. /// @@ -220,6 +271,21 @@ public class TrackEntity : IStorageEntity, IAuditableEntity /// public HashSet Tags { get; set; } = []; + /// + /// Gets or sets the status of the metadata enrichment of the track. + /// + public MetadataStatus MetadataStatus { get; set; } + + /// + /// Gets or sets the date and time when the metadata of the track was last enriched. + /// + public DateTime? LastMetadataUpdateUtc { get; set; } + + /// + /// Gets or sets the name of the plugin that enriched the metadata of the track. + /// + public string? MetadataProvider { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkIswcEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkIswcEntity.cs new file mode 100644 index 00000000..dbcfae5b --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkIswcEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for an ISWC (International Standard Musical Work Code) of the work a track is a recording of. +/// +/// The value of the ISWC. +[DebuggerDisplay("Value: {Value}")] +public record TrackWorkIswcEntity( + string Value +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkLanguageEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkLanguageEntity.cs new file mode 100644 index 00000000..ff7197c1 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkLanguageEntity.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for a language of the work a track is a recording of. +/// +/// The ISO 639-1 two-letter language code. +/// The full name of the language in English. +/// The native name of the language, if applicable. +[DebuggerDisplay("LanguageCode: {LanguageCode}")] +public record TrackWorkLanguageEntity( + string LanguageCode, + string LanguageName, + string? NativeName +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs index 3dfdaa16..993b48a4 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs @@ -45,6 +45,11 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity /// public required ICollection ContentLocations { get; init; } = []; + /// + /// Gets the ordered parts of the template describing the structure of the media library on disk. + /// + public ICollection PathTemplateParts { get; init; } = []; + /// /// Gets the list of scans of the media library. /// @@ -87,6 +92,12 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity /// public string? ArtworkProvidersConfigurationFingerprint { get; set; } + /// + /// Gets or sets the fingerprint of the path template of the media library, used to detect whether the template + /// changed since the last scan, and thus whether the metadata needs to be derived from the paths again. + /// + public string? PathTemplateFingerprint { get; set; } + /// /// Gets the user that owns the media library. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntity.cs new file mode 100644 index 00000000..dfa26b26 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntity.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Repository entity for one part of the path template of a media library. +/// +[DebuggerDisplay("Kind: {Kind}; Position: {Position}")] +public class LibraryPathTemplatePartEntity +{ + /// + /// Gets or sets the zero based position of the part in the path template. + /// + public required int Position { get; set; } + + /// + /// Gets or sets the kind of the path part. + /// + public required LibraryPathPartKind Kind { get; set; } + + /// + /// Gets or sets the literal text or the value mask of the path part. + /// + public required string Representation { get; set; } + + /// + /// Gets or sets whether the path part can be absent from the path. + /// + public required bool IsOptional { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs index 45779d8a..0cd1b059 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs index 718dc8cb..877e541b 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs @@ -47,6 +47,11 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity /// public bool ShouldAggregateMetadataWhenMissing { get; set; } + /// + /// Gets or sets whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. + /// + public bool ShouldAggregateArtworkWhenMissing { get; set; } + /// /// Gets or sets whether PDF books are rendered as page images for the user, or not. Rendering PDFs as images preserves the /// original layout, but the pages are not selectable or searchable, unlike their text layer. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs index 64ddf7cd..56ebf0c6 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs @@ -40,6 +40,15 @@ public interface IBookRepository : IRepository, /// An containing either the stored at the provided path, or an error. Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); + /// + /// Gets the subset of that is already used by a book of the library identified by . + /// + /// The Id of the library whose books are searched. + /// The book paths to check. + /// Cancellation token that can be used to stop the execution. + /// An containing either the paths that are already used, or an error. + Task>> GetExistingPathsAsync(Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken); + /// /// Gets a page of the books of the media library identified by whose metadata has not been enriched yet, /// ordered by path, using keyset pagination. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs index 4cc72122..179da525 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs @@ -33,4 +33,12 @@ public interface ILibraryScanRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An containing either a collection of , or an error. Task>> GetRunningScansAsync(CancellationToken cancellationToken); + + /// + /// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still + /// or , as failed. + /// + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> FailInterruptedScansAsync(CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs index 8c042ba8..1174a464 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs @@ -55,6 +55,15 @@ public interface ILibraryScanStagingResultsRepository : IRepositoryAn containing either the paths of the changed staging results, or an error. Task>> GetChangedPathsAsync(Guid scanId, CancellationToken cancellationToken); + /// + /// Gets the paths of the media library scan staging results of the current scan that are new or changed, meaning they need their content hashed + /// and their metadata extracted. + /// + /// The unique identifier of the media library scan whose staging result paths are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the paths of the staging results that need rehashing, or an error. + Task>> GetPathsNeedingRehashAsync(Guid scanId, CancellationToken cancellationToken); + /// /// Updates the content hashes of the provided media library scan staging results. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs index f4103045..4ad209be 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs @@ -20,7 +20,8 @@ public interface IAlbumRepository : IRepository, IInsertRepositoryAction, IUpdateRepositoryAction, IApplyUpdateRepositoryAction, - IGetByIdRepositoryAction + IGetByIdRepositoryAction, + IDeleteByIdRepositoryAction { /// /// Gets all the albums of the artist identified by . @@ -38,4 +39,67 @@ public interface IAlbumRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An containing either a paginated result of , or an error. Task>> GetAlbumsLiteByArtistIdAsync(Guid artistId, PaginationDataDto? paginationData, CancellationToken cancellationToken); + + /// + /// Gets the album of the artist identified by that has the provided . + /// + /// The Id of the artist whose album is retrieved. + /// The title of the album to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either the with the provided title, or an error. + Task> GetByTitleAsync(Guid artistId, string title, CancellationToken cancellationToken); + + /// + /// Gets the album of the artist identified by that owns a track stored in the provided . + /// + /// The Id of the artist whose album is retrieved. + /// The file system path of the album directory the album owns. + /// Cancellation token that can be used to stop the execution. + /// An containing either the owning the directory, or an error. + Task> GetByTrackDirectoryAsync(Guid artistId, string directoryPath, CancellationToken cancellationToken); + + /// + /// Gets the number of albums of the media library identified by whose metadata has not been enriched yet. + /// + /// The Id of the media library whose albums are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of albums needing their metadata enriched, or an error. + Task> GetAlbumsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the number of albums of the media library identified by whose artwork has not been resolved yet, + /// meaning they have no artwork that is either enriched or confirmed as unavailable. + /// + /// The Id of the media library whose albums are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of albums needing their artwork resolved, or an error. + Task> GetAlbumsNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets a page of the albums of the media library identified by whose artwork has not been resolved yet, + /// together with their artist, ordered by Id, excluding the provided albums. + /// + /// The Id of the media library whose albums are retrieved. + /// The Ids of the albums that were already processed in the current run and must not be retrieved again. + /// The maximum number of albums to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of albums needing their artwork resolved, or an error. + Task>> GetAlbumsNeedingArtworkAsync(Guid libraryId, IReadOnlyCollection excludedAlbumIds, int pageSize, CancellationToken cancellationToken); + + /// + /// Gets the file system path of one track of each of the albums identified by , keyed by the Id of the album. + /// + /// The Ids of the albums whose track path is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the file system path of a track of each album, or an error. + Task>> GetFirstTrackPathsByAlbumIdsAsync(IReadOnlyCollection albumIds, CancellationToken cancellationToken); + + /// + /// Resets the metadata enrichment status of all the albums of the media library identified by , + /// so that they are re-enriched, because the metadata provider configuration of the library changed. + /// + /// The Id of the media library whose albums are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs index b15e7717..1cc604ac 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs @@ -3,7 +3,11 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; #endregion namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; @@ -19,4 +23,59 @@ public interface IArtistRepository : IRepository, IGetAllLiteRepositoryAction, IDeleteByIdRepositoryAction { + /// + /// Gets the artist of the library identified by that has the provided . + /// + /// The Id of the library whose artist is retrieved. + /// The name of the artist to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either the with the provided name, or an error. + Task> GetByNameAsync(Guid libraryId, string name, CancellationToken cancellationToken); + + /// + /// Gets a page of the artists of the media library identified by whose metadata has not been enriched yet, + /// together with their albums and tracks and the collections needed to enrich them, ordered by name, using keyset pagination. + /// + /// The Id of the media library whose artists are retrieved. + /// The name of the last retrieved artist, used for keyset pagination. Pass to get the first page. + /// The maximum number of artists to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of artists needing their metadata enriched, or an error. + Task>> GetArtistsNeedingMetadataAsync(Guid libraryId, string? lastName, int pageSize, CancellationToken cancellationToken); + + /// + /// Gets the number of artists of the media library identified by whose metadata has not been enriched yet. + /// + /// The Id of the media library whose artists are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of artists needing their metadata enriched, or an error. + Task> GetArtistsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the number of artists of the media library identified by whose artwork has not been resolved yet. + /// + /// The Id of the media library whose artists are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of artists needing their artwork resolved, or an error. + Task> GetArtistsNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets a page of the artists of the media library identified by whose artwork has not been resolved yet, + /// together with their albums and tracks, ordered by name, using keyset pagination. + /// + /// The Id of the media library whose artists are retrieved. + /// The name of the last retrieved artist, used for keyset pagination. Pass to get the first page. + /// The maximum number of artists to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of artists needing their artwork resolved, or an error. + Task>> GetArtistsNeedingArtworkAsync(Guid libraryId, string? lastName, int pageSize, CancellationToken cancellationToken); + + /// + /// Resets the metadata enrichment status of all the artists of the media library identified by , + /// so that they are re-enriched, because the metadata provider configuration of the library changed. + /// + /// The Id of the media library whose artists are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs new file mode 100644 index 00000000..2d1686e8 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +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.Common.DataAccess.Repositories.MusicLibrary; + +/// +/// Interface for the repository for the artwork of the music library items. +/// +public interface IMusicArtworkRepository : IRepository, + IInsertRangeRepositoryAction +{ + /// + /// Gets the pieces of artwork owned by the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken); + + /// + /// Deletes all the pieces of artwork owned by the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken); + + /// + /// Resets the artwork enrichment status of all the pieces of artwork owned by the music library items of the media library identified by , so that they are re-resolved. + /// + /// + /// The status is reset because the artwork provider configuration of the library changed. + /// + /// The Id of the media library whose artwork is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicLibraryScanItemMetadataRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicLibraryScanItemMetadataRepository.cs new file mode 100644 index 00000000..488c0d9c --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicLibraryScanItemMetadataRepository.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; + +/// +/// Interface for the repository for the music metadata staged during a media library scan. +/// +public interface IMusicLibraryScanItemMetadataRepository : IRepository, + IInsertRangeRepositoryAction +{ + /// + /// Gets all the staged music metadata items of the media library scan identified by . + /// + /// The Id of the media library scan whose staged music metadata is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByScanIdAsync(Guid scanId, CancellationToken cancellationToken); + + /// + /// Deletes all the staged music metadata items of the media library scan identified by . + /// + /// The Id of the media library scan whose staged music metadata is deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByScanIdAsync(Guid scanId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs index b2720f5f..72f1b185 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -20,7 +20,8 @@ public interface ITrackRepository : IRepository, IInsertRepositoryAction, IUpdateRepositoryAction, IApplyUpdateRepositoryAction, - IGetByIdRepositoryAction + IGetByIdRepositoryAction, + IDeleteByIdRepositoryAction { /// /// Gets the subset of that is already used by a track of the library identified by . @@ -47,4 +48,40 @@ public interface ITrackRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An containing either a paginated result of , or an error. Task>> GetTracksLiteByAlbumIdAsync(Guid albumId, PaginationDataDto? paginationData, CancellationToken cancellationToken); + + /// + /// Gets the track of the library identified by that is stored at the provided . + /// + /// The Id of the library whose track is retrieved. + /// The file system path of the track to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either the stored at the provided path, or an error. + Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); + + /// + /// Resets the enrichment state of the tracks stored at the provided in the media library identified by + /// , together with their albums and artists, so that they are re-enriched, because their content changed since the last scan. + /// + /// The Id of the media library whose tracks are reset. + /// The file system paths of the tracks whose enrichment state is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken); + + /// + /// Gets the number of tracks of the media library identified by whose metadata has not been enriched yet. + /// + /// The Id of the media library whose tracks are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of tracks needing their metadata enriched, or an error. + Task> GetTracksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Resets the metadata enrichment status of all the tracks of the media library identified by , + /// so that they are re-enriched, because the metadata provider configuration of the library changed. + /// + /// The Id of the media library whose tracks are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index f944b9f4..0290d2a0 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -60,6 +60,16 @@ public interface IUnitOfWork /// ITrackRepository TrackRepository { get; } + /// + /// Gets the repository for the artwork of the music library items. + /// + IMusicArtworkRepository MusicArtworkRepository { get; } + + /// + /// Gets the repository for the music metadata staged during a media library scan. + /// + IMusicLibraryScanItemMetadataRepository MusicLibraryScanItemMetadataRepository { get; } + /// /// Gets the media contributor repository. /// diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 306cfeb9..6ca6bec2 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Telemetry; +using Lumina.Application.Core.MediaLibrary.Management.Deletion; using Lumina.Domain.Common.Events; using Microsoft.Extensions.DependencyInjection; using System; @@ -41,6 +42,9 @@ public static class ApplicationLayerServices (implementation, contract) => new { Contract = contract, Implementation = implementation }) .Where(registration => registration.Contract.IsGenericType && handlerContractTypes.Contains(registration.Contract.GetGenericTypeDefinition())); + services.AddScoped(); + services.AddScoped(); + foreach (var registration in handlerRegistrations) { if (services.Any(service => service.ServiceType == registration.Contract)) diff --git a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs index c77c25f4..67fa84a6 100644 --- a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs +++ b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs @@ -26,4 +26,9 @@ public class MediaSettingsDto /// Gets or sets the directory where the media item files are stored. /// public required string BooksDirectory { get; init; } + + /// + /// Gets or sets the directory where the music library item files are stored. + /// + public required string MusicDirectory { get; init; } } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs index 6bcb848b..0b27e6ad 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs @@ -20,7 +20,7 @@ public static class GenreDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this GenreDto dto) + public static Result ToDomainValueObject(this GenreDto dto) { return Genre.Create( dto.Name! @@ -34,8 +34,8 @@ public static class GenreDtoMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainValueObjects(this IEnumerable dtos) { - return dtos.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + return dtos.Select(repositoryEntity => repositoryEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs index 535adbcd..19581a8a 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs @@ -43,7 +43,7 @@ public static class GenreEntityMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this GenreEntity repositoryEntity) + public static Result ToDomainValueObject(this GenreEntity repositoryEntity) { return Genre.Create( repositoryEntity.Name! @@ -57,8 +57,8 @@ public static class GenreEntityMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainValueObjects(this IEnumerable repositoryEntities) { - return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/LanguageInfoDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/LanguageInfoDtoMapping.cs index b466101a..84bd6b69 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/LanguageInfoDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/LanguageInfoDtoMapping.cs @@ -18,7 +18,7 @@ public static class LanguageInfoDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this LanguageInfoDto dto) + public static Result ToDomainValueObject(this LanguageInfoDto dto) { return LanguageInfo.Create( dto.LanguageCode!, diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/ReleaseInfoDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/ReleaseInfoDtoMapping.cs index 366900cf..3a68c20a 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/ReleaseInfoDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/ReleaseInfoDtoMapping.cs @@ -20,7 +20,7 @@ public static class ReleaseInfoDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this ReleaseInfoDto dto) + public static Result ToDomainValueObject(this ReleaseInfoDto dto) { return ReleaseInfo.Create( Optional.FromNullable(dto.OriginalReleaseDate), diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs index b86a6b7a..c1331f07 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs @@ -20,7 +20,7 @@ public static class TagDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this TagDto dto) + public static Result ToDomainValueObject(this TagDto dto) { return Tag.Create( dto.Name! @@ -34,8 +34,8 @@ public static class TagDtoMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainValueObjects(this IEnumerable dtos) { - return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); + return dtos.Select(domainEntity => domainEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs index 04753f6e..bec0b335 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs @@ -43,7 +43,7 @@ public static class TagEntityMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this TagEntity repositoryEntity) + public static Result ToDomainValueObject(this TagEntity repositoryEntity) { return Tag.Create( repositoryEntity.Name! @@ -57,8 +57,8 @@ public static class TagEntityMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainValueObjects(this IEnumerable repositoryEntities) { - return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMapping.cs index 98c99dcc..c34e0aa6 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMapping.cs @@ -3,7 +3,7 @@ using Lumina.Application.Common.Mapping.MediaContributors; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; -using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; @@ -30,16 +30,17 @@ public static class AddAlbumCommandMapping /// public static Result ToDomainEntity(this AddAlbumCommand command) { - Result metadataResult = command.Metadata!.ToDomainEntity(); + MusicAlbumMetadataDto metadata = command.Metadata!; + Result metadataResult = metadata.ToDomainValueObject(); if (metadataResult.IsFailure) return metadataResult.Errors; - IEnumerable> domainContributorsResult = command.Contributors!.ToMusicDomainEntities(); + IEnumerable> domainContributorsResult = (command.Contributors ?? []).ToMusicDomainEntities(); List errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + IEnumerable> domainRatingsResult = (command.Ratings ?? []).ToDomainValueObjects(); errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count > 0) return errors; @@ -78,9 +79,14 @@ public static class AddAlbumCommandMapping return Album.Create( AlbumId.Create(command.AlbumId.Value), metadataResult.Value, + Optional.FromNullable(metadata.Disambiguation), Optional.FromNullable(command.MediaFormat), + Optional.FromNullable(command.Packaging), + Optional.FromNullable(metadata.Script), barcode, - Optional.FromNullable(command.CatalogNumber), + command.CatalogNumbers ?? [], + Optional.FromNullable(command.Label), + Optional.FromNullable(command.ASIN), musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId, @@ -92,9 +98,14 @@ public static class AddAlbumCommandMapping return Album.Create( metadataResult.Value, + Optional.FromNullable(metadata.Disambiguation), Optional.FromNullable(command.MediaFormat), + Optional.FromNullable(command.Packaging), + Optional.FromNullable(metadata.Script), barcode, - Optional.FromNullable(command.CatalogNumber), + command.CatalogNumbers ?? [], + Optional.FromNullable(command.Label), + Optional.FromNullable(command.ASIN), musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMapping.cs index f769a908..7b4637e6 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMapping.cs @@ -27,8 +27,11 @@ public static class AddAlbumRequestMapping artistId, request.Metadata, request.MediaFormat, + request.Packaging, request.Barcode, - request.CatalogNumber, + request.CatalogNumbers, + request.Label, + request.ASIN, request.MusicBrainzReleaseId, request.MusicBrainzReleaseGroupId, request.MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs index 4335d734..add81757 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; @@ -16,10 +18,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; using System.Collections.Generic; using System.Linq; -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.Common; -using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; @@ -49,7 +47,7 @@ public static class AlbumEntityMapping return releaseInfoResult.Errors; List domainGenres = []; - foreach (Result genreResult in repositoryEntity.Genres.ToDomainEntities()) + foreach (Result genreResult in repositoryEntity.Genres.ToDomainValueObjects()) { if (genreResult.IsFailure) return genreResult.Errors; @@ -57,7 +55,7 @@ public static class AlbumEntityMapping } List domainTags = []; - foreach (Result tagResult in repositoryEntity.Tags.ToDomainEntities()) + foreach (Result tagResult in repositoryEntity.Tags.ToDomainValueObjects()) { if (tagResult.IsFailure) return tagResult.Errors; @@ -75,13 +73,14 @@ public static class AlbumEntityMapping Result metadataResult = AlbumMetadata.Create( repositoryEntity.Title, Optional.FromNullable(repositoryEntity.OriginalTitle), + Optional.FromNullable(repositoryEntity.ReleaseTitle), Optional.FromNullable(repositoryEntity.Description), releaseInfoResult.Value, domainGenres, domainTags, language, originalLanguage, - Optional.FromNullable(repositoryEntity.ReleaseType), + [.. repositoryEntity.ReleaseTypes.Select(releaseType => releaseType.ReleaseType)], Optional.FromNullable(repositoryEntity.ReleaseStatus), Optional.FromNullable(repositoryEntity.TotalDiscs), repositoryEntity.TotalTracks); @@ -108,7 +107,7 @@ public static class AlbumEntityMapping musicBrainzReleaseArtistId = MusicBrainzId.Create(repositoryEntity.MusicBrainzReleaseArtistId.Value); List domainRatings = []; - foreach (Result ratingResult in repositoryEntity.Ratings.ToDomainEntities()) + foreach (Result ratingResult in repositoryEntity.Ratings.ToDomainValueObjects()) { if (ratingResult.IsFailure) return ratingResult.Errors; @@ -136,9 +135,14 @@ public static class AlbumEntityMapping return Album.Create( AlbumId.Create(repositoryEntity.Id), metadataResult.Value, + Optional.FromNullable(repositoryEntity.Disambiguation), Optional.FromNullable(repositoryEntity.MediaFormat), + Optional.FromNullable(repositoryEntity.Packaging), + Optional.FromNullable(repositoryEntity.Script), barcode, - Optional.FromNullable(repositoryEntity.CatalogNumber), + [.. repositoryEntity.CatalogNumbers.Select(catalogNumber => catalogNumber.CatalogNumber)], + Optional.FromNullable(repositoryEntity.Label), + Optional.FromNullable(repositoryEntity.ASIN), musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId, @@ -181,19 +185,22 @@ public static class AlbumEntityMapping repositoryEntity.OriginalLanguageName, repositoryEntity.OriginalLanguageNativeName ) : null; - AlbumMetadataDto metadata = new( + MusicAlbumMetadataDto metadata = new( repositoryEntity.Title, repositoryEntity.OriginalTitle, repositoryEntity.Description, + repositoryEntity.Disambiguation, releaseInfo, languageInfo, originalLanguageInfo, [.. repositoryEntity.Tags.ToResponses()], [.. repositoryEntity.Genres.ToResponses()], - repositoryEntity.ReleaseType, + repositoryEntity.Script, + [.. repositoryEntity.ReleaseTypes.Select(releaseType => releaseType.ReleaseType)], repositoryEntity.ReleaseStatus, repositoryEntity.TotalDiscs, - repositoryEntity.TotalTracks + repositoryEntity.TotalTracks, + repositoryEntity.ReleaseTitle ); return new AlbumResponse( repositoryEntity.Id, @@ -201,8 +208,11 @@ public static class AlbumEntityMapping repositoryEntity.LibraryId, metadata, repositoryEntity.MediaFormat, + repositoryEntity.Packaging, repositoryEntity.Barcode, - repositoryEntity.CatalogNumber, + repositoryEntity.CatalogNumbers.Count > 0 ? [.. repositoryEntity.CatalogNumbers.Select(catalogNumber => catalogNumber.CatalogNumber)] : null, + repositoryEntity.Label, + repositoryEntity.ASIN, repositoryEntity.MusicBrainzReleaseId, repositoryEntity.MusicBrainzReleaseGroupId, repositoryEntity.MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMapping.cs index 9a2cd2df..d8eca969 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMapping.cs @@ -33,7 +33,9 @@ public static class AlbumMapping LibraryId = libraryId, Title = domainEntity.Metadata.Title, OriginalTitle = domainEntity.Metadata.OriginalTitle.HasValue ? domainEntity.Metadata.OriginalTitle.Value : null, + ReleaseTitle = domainEntity.Metadata.ReleaseTitle.HasValue ? domainEntity.Metadata.ReleaseTitle.Value : null, Description = domainEntity.Metadata.Description.HasValue ? domainEntity.Metadata.Description.Value : null, + Disambiguation = domainEntity.Disambiguation.HasValue ? domainEntity.Disambiguation.Value : null, OriginalReleaseDate = domainEntity.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? domainEntity.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null, OriginalReleaseYear = domainEntity.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? domainEntity.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null, ReReleaseDate = domainEntity.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? domainEntity.Metadata.ReleaseInfo.ReReleaseDate.Value : null, @@ -46,15 +48,19 @@ public static class AlbumMapping OriginalLanguageCode = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.LanguageCode : null, OriginalLanguageName = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.LanguageName : null, OriginalLanguageNativeName = domainEntity.Metadata.OriginalLanguage.HasValue && domainEntity.Metadata.OriginalLanguage.Value.NativeName.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.NativeName.Value : null, + Script = domainEntity.Script.HasValue ? domainEntity.Script.Value : null, Genres = [.. domainEntity.Metadata.Genres.ToRepositoryEntities()], Tags = [.. domainEntity.Metadata.Tags.ToRepositoryEntities()], - ReleaseType = domainEntity.Metadata.ReleaseType.HasValue ? domainEntity.Metadata.ReleaseType.Value : null, + ReleaseTypes = [.. domainEntity.Metadata.ReleaseTypes.Select(releaseType => new AlbumReleaseTypeEntity(releaseType))], ReleaseStatus = domainEntity.Metadata.ReleaseStatus.HasValue ? domainEntity.Metadata.ReleaseStatus.Value : null, TotalDiscs = domainEntity.Metadata.TotalDiscs.HasValue ? domainEntity.Metadata.TotalDiscs.Value : null, TotalTracks = domainEntity.Metadata.TotalTracks, MediaFormat = domainEntity.MediaFormat.HasValue ? domainEntity.MediaFormat.Value : null, + Packaging = domainEntity.Packaging.HasValue ? domainEntity.Packaging.Value : null, Barcode = domainEntity.Barcode.HasValue ? domainEntity.Barcode.Value.Value : null, - CatalogNumber = domainEntity.CatalogNumber.HasValue ? domainEntity.CatalogNumber.Value : null, + CatalogNumbers = [.. domainEntity.CatalogNumbers.Select(catalogNumber => new AlbumCatalogNumberEntity(catalogNumber))], + Label = domainEntity.Label.HasValue ? domainEntity.Label.Value : null, + ASIN = domainEntity.ASIN.HasValue ? domainEntity.ASIN.Value : null, MusicBrainzReleaseId = domainEntity.MusicBrainzReleaseId.HasValue ? domainEntity.MusicBrainzReleaseId.Value.Value : null, MusicBrainzReleaseGroupId = domainEntity.MusicBrainzReleaseGroupId.HasValue ? domainEntity.MusicBrainzReleaseGroupId.Value.Value : null, MusicBrainzReleaseArtistId = domainEntity.MusicBrainzReleaseArtistId.HasValue ? domainEntity.MusicBrainzReleaseArtistId.Value.Value : null, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMapping.cs index 84c3e609..0b8580f1 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMapping.cs @@ -1,9 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; @@ -18,42 +23,126 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibra /// public static class AlbumMetadataDtoMapping { + /// + /// Applies the metadata of to , through the owning aggregate root. + /// + /// The album metadata to apply. + /// The artist aggregate that owns the album. + /// The album entity to update. + /// The media contributors of the album, already resolved to their persisted identifiers. + /// + /// An containing either the successfully updated , or an error message. + /// + public static Result ApplyTo(this AlbumMetadataDto dto, Artist artist, Album album, IReadOnlyCollection contributors) + { + Result metadataResult = dto.ToDomainValueObject(album.Metadata.ReleaseInfo); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + List ratings = []; + foreach (AudioRatingDto rating in dto.Ratings ?? []) + { + Result ratingResult = rating.ToDomainValueObject(); + if (ratingResult.IsFailure) + return ratingResult.Errors; + ratings.Add(ratingResult.Value); + } + + Optional barcode = Optional.None(); + if (!string.IsNullOrWhiteSpace(dto.Barcode)) + { + Result barcodeResult = Barcode.Create(dto.Barcode); + if (barcodeResult.IsFailure) + return barcodeResult.Errors; + barcode = barcodeResult.Value; + } + + Optional musicBrainzReleaseId = Optional.None(); + if (dto.MusicBrainzReleaseId is not null) + musicBrainzReleaseId = MusicBrainzId.Create(dto.MusicBrainzReleaseId.Value); + Optional musicBrainzReleaseGroupId = Optional.None(); + if (dto.MusicBrainzReleaseGroupId is not null) + musicBrainzReleaseGroupId = MusicBrainzId.Create(dto.MusicBrainzReleaseGroupId.Value); + Optional musicBrainzReleaseArtistId = Optional.None(); + if (dto.MusicBrainzReleaseArtistId is not null) + musicBrainzReleaseArtistId = MusicBrainzId.Create(dto.MusicBrainzReleaseArtistId.Value); + + return artist.UpdateAlbum( + album, + metadataResult.Value, + Optional.FromNullable(dto.Disambiguation), + Optional.FromNullable(dto.MediaFormat), + Optional.FromNullable(dto.Packaging), + Optional.FromNullable(dto.Script), + barcode, + dto.CatalogNumbers ?? [], + Optional.FromNullable(dto.Label), + Optional.FromNullable(dto.ASIN), + musicBrainzReleaseId, + musicBrainzReleaseGroupId, + musicBrainzReleaseArtistId, + contributors, + ratings); + } + /// /// Converts to a domain . /// /// The data transfer object to be converted. + /// The release information already stored for the album, used as a fallback for the fields the metadata does not provide. /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this AlbumMetadataDto dto) + private static Result ToDomainValueObject(this AlbumMetadataDto dto, ReleaseInfo existingReleaseInfo) { ReleaseInfoDto? releaseInfoDto = dto.ReleaseInfo; + + // The enrichment must not erase a release date that the tags already provided, so a date that the metadata does not carry falls back to the stored one. + DateOnly? originalReleaseDate = releaseInfoDto?.OriginalReleaseDate; + int? originalReleaseYear = releaseInfoDto?.OriginalReleaseYear; + if (originalReleaseDate is null && originalReleaseYear is null) + { + originalReleaseDate = existingReleaseInfo.OriginalReleaseDate.HasValue ? existingReleaseInfo.OriginalReleaseDate.Value : null; + originalReleaseYear = existingReleaseInfo.OriginalReleaseYear.HasValue ? existingReleaseInfo.OriginalReleaseYear.Value : null; + } + + DateOnly? reReleaseDate = releaseInfoDto?.ReReleaseDate; + int? reReleaseYear = releaseInfoDto?.ReReleaseYear; + if (reReleaseDate is null && reReleaseYear is null) + { + reReleaseDate = existingReleaseInfo.ReReleaseDate.HasValue ? existingReleaseInfo.ReReleaseDate.Value : null; + reReleaseYear = existingReleaseInfo.ReReleaseYear.HasValue ? existingReleaseInfo.ReReleaseYear.Value : null; + } + + ReleaseCountry? releaseCountry = releaseInfoDto?.ReleaseCountry ?? (existingReleaseInfo.ReleaseCountry.HasValue ? existingReleaseInfo.ReleaseCountry.Value : null); + string? releaseVersion = releaseInfoDto?.ReleaseVersion ?? (existingReleaseInfo.ReleaseVersion.HasValue ? existingReleaseInfo.ReleaseVersion.Value : null); + Result releaseInfoResult = ReleaseInfo.Create( - Optional.FromNullable(releaseInfoDto?.OriginalReleaseDate), - Optional.FromNullable(releaseInfoDto?.OriginalReleaseYear), - Optional.FromNullable(releaseInfoDto?.ReReleaseDate), - Optional.FromNullable(releaseInfoDto?.ReReleaseYear), - Optional.FromNullable(releaseInfoDto?.ReleaseCountry), - Optional.FromNullable(releaseInfoDto?.ReleaseVersion)); + Optional.FromNullable(originalReleaseDate), + Optional.FromNullable(originalReleaseYear), + Optional.FromNullable(reReleaseDate), + Optional.FromNullable(reReleaseYear), + Optional.FromNullable(releaseCountry), + Optional.FromNullable(releaseVersion)); if (releaseInfoResult.IsFailure) return releaseInfoResult.Errors; - List domainGenres = []; + List genres = []; foreach (GenreDto genre in dto.Genres ?? []) { - Result genreResult = genre.ToDomainEntity(); + Result genreResult = genre.ToDomainValueObject(); if (genreResult.IsFailure) return genreResult.Errors; - domainGenres.Add(genreResult.Value); + genres.Add(genreResult.Value); } - List domainTags = []; + List tags = []; foreach (TagDto tag in dto.Tags ?? []) { - Result tagResult = tag.ToDomainEntity(); + Result tagResult = tag.ToDomainValueObject(); if (tagResult.IsFailure) return tagResult.Errors; - domainTags.Add(tagResult.Value); + tags.Add(tagResult.Value); } Optional language = Optional.None(); @@ -67,13 +156,14 @@ public static class AlbumMetadataDtoMapping return AlbumMetadata.Create( dto.Title!, Optional.FromNullable(dto.OriginalTitle), + Optional.FromNullable(dto.ReleaseTitle), Optional.FromNullable(dto.Description), releaseInfoResult.Value, - domainGenres, - domainTags, + genres, + tags, language, originalLanguage, - Optional.FromNullable(dto.ReleaseType), + dto.ReleaseTypes is null ? [] : [.. dto.ReleaseTypes], Optional.FromNullable(dto.ReleaseStatus), Optional.FromNullable(dto.TotalDiscs), dto.TotalTracks ?? 0); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/MusicAlbumMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/MusicAlbumMetadataDtoMapping.cs new file mode 100644 index 00000000..9c75a4ea --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/MusicAlbumMetadataDtoMapping.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Extension methods for converting . +/// +public static class MusicAlbumMetadataDtoMapping +{ + /// + /// Converts to a domain . + /// + /// The data transfer object to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainValueObject(this MusicAlbumMetadataDto dto) + { + ReleaseInfoDto? releaseInfoDto = dto.ReleaseInfo; + Result releaseInfoResult = ReleaseInfo.Create( + Optional.FromNullable(releaseInfoDto?.OriginalReleaseDate), + Optional.FromNullable(releaseInfoDto?.OriginalReleaseYear), + Optional.FromNullable(releaseInfoDto?.ReReleaseDate), + Optional.FromNullable(releaseInfoDto?.ReReleaseYear), + Optional.FromNullable(releaseInfoDto?.ReleaseCountry), + Optional.FromNullable(releaseInfoDto?.ReleaseVersion)); + if (releaseInfoResult.IsFailure) + return releaseInfoResult.Errors; + + List domainGenres = []; + foreach (GenreDto genre in dto.Genres ?? []) + { + Result genreResult = genre.ToDomainValueObject(); + if (genreResult.IsFailure) + return genreResult.Errors; + domainGenres.Add(genreResult.Value); + } + + List domainTags = []; + foreach (TagDto tag in dto.Tags ?? []) + { + Result tagResult = tag.ToDomainValueObject(); + if (tagResult.IsFailure) + return tagResult.Errors; + domainTags.Add(tagResult.Value); + } + + Optional language = Optional.None(); + if (dto.Language is not null && dto.Language.LanguageCode is not null && dto.Language.LanguageName is not null) + language = LanguageInfo.Create(dto.Language.LanguageCode, dto.Language.LanguageName, Optional.FromNullable(dto.Language.NativeName)); + + Optional originalLanguage = Optional.None(); + 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.FromNullable(dto.OriginalLanguage.NativeName)); + + return AlbumMetadata.Create( + dto.Title!, + Optional.FromNullable(dto.OriginalTitle), + Optional.FromNullable(dto.ReleaseTitle), + Optional.FromNullable(dto.Description), + releaseInfoResult.Value, + domainGenres, + domainTags, + language, + originalLanguage, + dto.ReleaseTypes is null ? [] : [.. dto.ReleaseTypes], + Optional.FromNullable(dto.ReleaseStatus), + Optional.FromNullable(dto.TotalDiscs), + dto.TotalTracks ?? 0); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMapping.cs index f7b8383e..33a265b2 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMapping.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.Mapping.MediaContributors; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; @@ -31,16 +32,17 @@ public static class UpdateAlbumCommandMapping /// public static Result ToDomainEntity(this UpdateAlbumCommand command, Artist artist) { - Result metadataResult = command.Metadata!.ToDomainEntity(); + MusicAlbumMetadataDto metadata = command.Metadata!; + Result metadataResult = metadata.ToDomainValueObject(); if (metadataResult.IsFailure) return metadataResult.Errors; - IEnumerable> domainContributorsResult = command.Contributors!.ToMusicDomainEntities(); + IEnumerable> domainContributorsResult = (command.Contributors ?? []).ToMusicDomainEntities(); List errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + IEnumerable> domainRatingsResult = (command.Ratings ?? []).ToDomainValueObjects(); errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count > 0) return errors; @@ -72,9 +74,14 @@ public static class UpdateAlbumCommandMapping Result updateResult = artist.UpdateAlbum( album, metadataResult.Value, + Optional.FromNullable(metadata.Disambiguation), Optional.FromNullable(command.MediaFormat), + Optional.FromNullable(command.Packaging), + Optional.FromNullable(metadata.Script), barcode, - Optional.FromNullable(command.CatalogNumber), + command.CatalogNumbers ?? [], + Optional.FromNullable(command.Label), + Optional.FromNullable(command.ASIN), musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMapping.cs index f75944de..77f345c0 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMapping.cs @@ -26,8 +26,11 @@ public static class UpdateAlbumRequestMapping albumId, request.Metadata, request.MediaFormat, + request.Packaging, request.Barcode, - request.CatalogNumber, + request.CatalogNumbers, + request.Label, + request.ASIN, request.MusicBrainzReleaseId, request.MusicBrainzReleaseGroupId, request.MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMapping.cs index 9eb4c57f..e485a8cc 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMapping.cs @@ -1,12 +1,18 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaContributors; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Collections.Generic; using System.Linq; @@ -29,8 +35,10 @@ public static class AddArtistCommandMapping /// public static Result ToDomainEntity(this AddArtistCommand command, Guid libraryId) { + MusicArtistMetadataDto metadata = command.Metadata!; + // Map the media contributors referenced by the user to their domain counterparts; a contributor is identified by its id and carries the role it played. - IEnumerable> domainContributorsResult = command.Contributors!.ToMusicDomainEntities(); + IEnumerable> domainContributorsResult = (command.Contributors ?? []).ToMusicDomainEntities(); List errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)]; if (errors.Count > 0) return errors; @@ -41,16 +49,61 @@ public static class AddArtistCommandMapping if (errors.Count > 0) return errors; - Optional website = Optional.FromNullable(command.Website); + IEnumerable> domainGenresResult = (metadata.Genres ?? []).ToDomainValueObjects(); + errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainTagsResult = (metadata.Tags ?? []).ToDomainValueObjects(); + errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainRatingsResult = (command.Ratings ?? []).ToDomainValueObjects(); + errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; + if (errors.Count > 0) + return errors; + + Result> areaResult = metadata.Area.ToDomainValueObject(); + if (areaResult.IsFailure) + return areaResult.Errors; + Result> beginAreaResult = metadata.BeginArea.ToDomainValueObject(); + if (beginAreaResult.IsFailure) + return beginAreaResult.Errors; + Result> endAreaResult = metadata.EndArea.ToDomainValueObject(); + if (endAreaResult.IsFailure) + return endAreaResult.Errors; + + Result> aliasesResult = metadata.Aliases.ToDomainValueObjects(); + if (aliasesResult.IsFailure) + return aliasesResult.Errors; + Optional musicBrainzArtistId = Optional.None(); if (command.MusicBrainzArtistId is not null) musicBrainzArtistId = MusicBrainzId.Create(command.MusicBrainzArtistId.Value); return Artist.Create( LibraryId.Create(libraryId), - command.Name!, - website, + metadata.Name!, + Optional.FromNullable(metadata.SortName), + Optional.FromNullable(metadata.Disambiguation), + Optional.FromNullable(metadata.Type), + Optional.FromNullable(metadata.Gender), + Optional.FromNullable(metadata.Country), + areaResult.Value, + beginAreaResult.Value, + endAreaResult.Value, + Optional.FromNullable(metadata.LifeSpanBegin), + Optional.FromNullable(metadata.LifeSpanEnd), + metadata.IsEnded, + Optional.FromNullable(command.Website), musicBrainzArtistId, + [.. (command.Ipis ?? [])], + [.. (command.Isnis ?? [])], + aliasesResult.Value, + [.. domainGenresResult.Select(genreResult => genreResult.Value)], + [.. domainTagsResult.Select(tagResult => tagResult.Value)], + [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)], [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)], [.. domainAlbumsResult.Select(albumResult => albumResult.Value)]); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMapping.cs index 29691f5e..0f53f64f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMapping.cs @@ -22,10 +22,13 @@ public static class AddArtistRequestMapping { return new AddArtistCommand( libraryId, - request.Name, + request.Metadata, request.Website, request.MusicBrainzArtistId, + request.Ipis, + request.Isnis, request.Contributors, + request.Ratings, request.Albums?.ToCommands(libraryId, null).ToList()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs index 14e4335d..bf1560ba 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs @@ -1,16 +1,22 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Collections.Generic; using System.Linq; @@ -36,6 +42,60 @@ public static class ArtistEntityMapping if (repositoryEntity.MusicBrainzArtistId is not null) musicBrainzArtistId = MusicBrainzId.Create(repositoryEntity.MusicBrainzArtistId.Value); + Optional area = Optional.None(); + if (repositoryEntity.Area is not null) + { + Result areaResult = repositoryEntity.Area.ToDomainValueObject(); + if (areaResult.IsFailure) + return areaResult.Errors; + area = areaResult.Value; + } + Optional beginArea = Optional.None(); + if (repositoryEntity.BeginArea is not null) + { + Result beginAreaResult = repositoryEntity.BeginArea.ToDomainValueObject(); + if (beginAreaResult.IsFailure) + return beginAreaResult.Errors; + beginArea = beginAreaResult.Value; + } + Optional endArea = Optional.None(); + if (repositoryEntity.EndArea is not null) + { + Result endAreaResult = repositoryEntity.EndArea.ToDomainValueObject(); + if (endAreaResult.IsFailure) + return endAreaResult.Errors; + endArea = endAreaResult.Value; + } + + Result> domainAliasesResult = repositoryEntity.Aliases.ToDomainValueObjects(); + if (domainAliasesResult.IsFailure) + return domainAliasesResult.Errors; + List domainAliases = domainAliasesResult.Value; + + List domainGenres = []; + foreach (Result genreResult in repositoryEntity.Genres.ToDomainValueObjects()) + { + if (genreResult.IsFailure) + return genreResult.Errors; + domainGenres.Add(genreResult.Value); + } + + List domainTags = []; + foreach (Result tagResult in repositoryEntity.Tags.ToDomainValueObjects()) + { + if (tagResult.IsFailure) + return tagResult.Errors; + domainTags.Add(tagResult.Value); + } + + List domainRatings = []; + foreach (Result ratingResult in repositoryEntity.Ratings.ToDomainValueObjects()) + { + if (ratingResult.IsFailure) + return ratingResult.Errors; + domainRatings.Add(ratingResult.Value); + } + List domainContributors = []; foreach (ArtistContributorEntity contributorEntity in repositoryEntity.Contributors) { @@ -58,8 +118,25 @@ public static class ArtistEntityMapping ArtistId.Create(repositoryEntity.Id), LibraryId.Create(repositoryEntity.LibraryId), repositoryEntity.Name, + Optional.FromNullable(repositoryEntity.SortName), + Optional.FromNullable(repositoryEntity.Disambiguation), + Optional.FromNullable(repositoryEntity.Type), + Optional.FromNullable(repositoryEntity.Gender), + Optional.FromNullable(repositoryEntity.Country), + area, + beginArea, + endArea, + Optional.FromNullable(repositoryEntity.LifeSpanBegin), + Optional.FromNullable(repositoryEntity.LifeSpanEnd), + repositoryEntity.IsEnded, Optional.FromNullable(repositoryEntity.Website), musicBrainzArtistId, + [.. repositoryEntity.Ipis.Select(ipi => ipi.Value)], + [.. repositoryEntity.Isnis.Select(isni => isni.Value)], + domainAliases, + domainGenres, + domainTags, + domainRatings, domainContributors, domainAlbums, repositoryEntity.CreatedOnUtc, @@ -73,16 +150,35 @@ public static class ArtistEntityMapping /// The converted response entity. public static ArtistResponse ToResponse(this ArtistEntity repositoryEntity) { + MusicArtistMetadataDto metadata = new( + repositoryEntity.Name, + repositoryEntity.SortName, + repositoryEntity.Disambiguation, + repositoryEntity.Type, + repositoryEntity.Gender, + repositoryEntity.Country, + repositoryEntity.Area.ToResponse(), + repositoryEntity.BeginArea.ToResponse(), + repositoryEntity.EndArea.ToResponse(), + repositoryEntity.LifeSpanBegin, + repositoryEntity.LifeSpanEnd, + repositoryEntity.IsEnded, + [.. repositoryEntity.Genres.ToResponses()], + [.. repositoryEntity.Tags.ToResponses()], + [.. repositoryEntity.Aliases.Select(alias => new MusicArtistAliasDto(alias.Name, alias.SortName, alias.Type, alias.Locale, alias.IsPrimary, alias.BeginDate, alias.EndDate, alias.IsEnded))]); return new ArtistResponse( repositoryEntity.Id, repositoryEntity.LibraryId, - repositoryEntity.Name, + metadata, repositoryEntity.Website, repositoryEntity.MusicBrainzArtistId, - [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], - [.. repositoryEntity.Albums.Select(album => album.ToResponse())], + [.. repositoryEntity.Ipis.Select(ipi => ipi.Value)], + [.. repositoryEntity.Isnis.Select(isni => isni.Value)], repositoryEntity.CreatedOnUtc, - repositoryEntity.UpdatedOnUtc); + repositoryEntity.UpdatedOnUtc, + [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], + [.. repositoryEntity.Ratings.ToResponses()], + [.. repositoryEntity.Albums.Select(album => album.ToResponse())]); } /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMapping.cs index 7081307f..01e02e5f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMapping.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using System; using System.Linq; @@ -25,8 +27,25 @@ public static class ArtistMapping Id = domainEntity.Id.Value, LibraryId = domainEntity.LibraryId.Value, Name = domainEntity.Name, + SortName = domainEntity.SortName.HasValue ? domainEntity.SortName.Value : null, + Disambiguation = domainEntity.Disambiguation.HasValue ? domainEntity.Disambiguation.Value : null, + Type = domainEntity.Type.HasValue ? domainEntity.Type.Value : null, + Gender = domainEntity.Gender.HasValue ? domainEntity.Gender.Value : null, + Country = domainEntity.Country.HasValue ? domainEntity.Country.Value : null, + LifeSpanBegin = domainEntity.LifeSpanBegin.HasValue ? domainEntity.LifeSpanBegin.Value : null, + LifeSpanEnd = domainEntity.LifeSpanEnd.HasValue ? domainEntity.LifeSpanEnd.Value : null, + IsEnded = domainEntity.IsEnded, Website = domainEntity.Website.HasValue ? domainEntity.Website.Value : null, MusicBrainzArtistId = domainEntity.MusicBrainzArtistId.HasValue ? domainEntity.MusicBrainzArtistId.Value.Value : null, + Area = domainEntity.Area.HasValue ? domainEntity.Area.Value.ToRepositoryEntity() : null, + BeginArea = domainEntity.BeginArea.HasValue ? domainEntity.BeginArea.Value.ToRepositoryEntity() : null, + EndArea = domainEntity.EndArea.HasValue ? domainEntity.EndArea.Value.ToRepositoryEntity() : null, + Aliases = [.. domainEntity.Aliases.ToRepositoryEntities()], + Ipis = [.. domainEntity.Ipis.Select(ipi => new ArtistIpiEntity(ipi))], + Isnis = [.. domainEntity.Isnis.Select(isni => new ArtistIsniEntity(isni))], + Genres = [.. domainEntity.Genres.ToRepositoryEntities()], + Tags = [.. domainEntity.Tags.ToRepositoryEntities()], + Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], Contributors = [.. domainEntity.Contributors.Select(contributor => new ArtistContributorEntity { Id = Guid.NewGuid(), diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMetadataDtoMapping.cs new file mode 100644 index 00000000..18750842 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMetadataDtoMapping.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class ArtistMetadataDtoMapping +{ + /// + /// Applies the metadata of to , through the aggregate root. + /// + /// The artist metadata to apply. + /// The artist aggregate the metadata is applied to. + /// The media contributors that make up the artist, already resolved to their persisted identifiers. + /// + /// An containing either the successfully updated , or an error message. + /// + public static Result ApplyTo(this ArtistMetadataDto dto, Artist artist, IReadOnlyCollection contributors) + { + Result> areaResult = dto.Area.ToDomainValueObject(); + if (areaResult.IsFailure) + return areaResult.Errors; + Result> beginAreaResult = dto.BeginArea.ToDomainValueObject(); + if (beginAreaResult.IsFailure) + return beginAreaResult.Errors; + Result> endAreaResult = dto.EndArea.ToDomainValueObject(); + if (endAreaResult.IsFailure) + return endAreaResult.Errors; + Result> aliasesResult = dto.Aliases.ToDomainValueObjects(); + if (aliasesResult.IsFailure) + return aliasesResult.Errors; + + List genres = []; + foreach (GenreDto genre in dto.Genres ?? []) + { + Result genreResult = genre.ToDomainValueObject(); + if (genreResult.IsFailure) + return genreResult.Errors; + genres.Add(genreResult.Value); + } + + List tags = []; + foreach (TagDto tag in dto.Tags ?? []) + { + Result tagResult = tag.ToDomainValueObject(); + if (tagResult.IsFailure) + return tagResult.Errors; + tags.Add(tagResult.Value); + } + + List ratings = []; + foreach (AudioRatingDto rating in dto.Ratings ?? []) + { + Result ratingResult = rating.ToDomainValueObject(); + if (ratingResult.IsFailure) + return ratingResult.Errors; + ratings.Add(ratingResult.Value); + } + + Optional musicBrainzArtistId = Optional.None(); + if (dto.MusicBrainzArtistId is not null) + musicBrainzArtistId = MusicBrainzId.Create(dto.MusicBrainzArtistId.Value); + + // The website is only replaced when the provider returned one, so a locally captured website is never cleared. + Optional website = string.IsNullOrWhiteSpace(dto.Website) ? artist.Website : Optional.FromNullable(dto.Website); + Result updateDetailsResult = artist.UpdateDetails( + string.IsNullOrWhiteSpace(dto.Name) ? artist.Name : dto.Name, + Optional.FromNullable(dto.SortName), + Optional.FromNullable(dto.Disambiguation), + Optional.FromNullable(dto.Type), + Optional.FromNullable(dto.Gender), + Optional.FromNullable(dto.Country), + areaResult.Value, + beginAreaResult.Value, + endAreaResult.Value, + Optional.FromNullable(dto.LifeSpanBegin), + Optional.FromNullable(dto.LifeSpanEnd), + dto.IsEnded, + website, + musicBrainzArtistId); + if (updateDetailsResult.IsFailure) + return updateDetailsResult.Errors; + + artist.UpdateAliases(aliasesResult.Value); + artist.UpdateIpis([.. dto.Ipis ?? []]); + artist.UpdateIsnis([.. dto.Isnis ?? []]); + artist.UpdateGenres(genres); + artist.UpdateTags(tags); + artist.UpdateRatings(ratings); + artist.UpdateContributors(contributors); + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMapping.cs index 5231db18..753848fc 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMapping.cs @@ -26,8 +26,11 @@ public static class UpdateArtistAlbumRequestMapping artistId, request.Metadata, request.MediaFormat, + request.Packaging, request.Barcode, - request.CatalogNumber, + request.CatalogNumbers, + request.Label, + request.ASIN, request.MusicBrainzReleaseId, request.MusicBrainzReleaseGroupId, request.MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs index 90cbb234..8b877823 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs @@ -1,11 +1,17 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaContributors; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Collections.Generic; using System.Linq; @@ -28,8 +34,10 @@ public static class UpdateArtistCommandMapping /// public static Result ToDomainEntity(this UpdateArtistCommand command, Artist artist) { + MusicArtistMetadataDto metadata = command.Metadata!; + // Map the media contributors that make up the artist to their domain counterparts. - IEnumerable> domainContributorsResult = command.Contributors!.ToMusicDomainEntities(); + IEnumerable> domainContributorsResult = (command.Contributors ?? []).ToMusicDomainEntities(); List errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)]; if (errors.Count > 0) return errors; @@ -40,15 +48,64 @@ public static class UpdateArtistCommandMapping if (errors.Count > 0) return errors; - Optional website = Optional.FromNullable(command.Website); + IEnumerable> domainGenresResult = (metadata.Genres ?? []).ToDomainValueObjects(); + errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainTagsResult = (metadata.Tags ?? []).ToDomainValueObjects(); + errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainRatingsResult = (command.Ratings ?? []).ToDomainValueObjects(); + errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; + if (errors.Count > 0) + return errors; + + Result> areaResult = metadata.Area.ToDomainValueObject(); + if (areaResult.IsFailure) + return areaResult.Errors; + Result> beginAreaResult = metadata.BeginArea.ToDomainValueObject(); + if (beginAreaResult.IsFailure) + return beginAreaResult.Errors; + Result> endAreaResult = metadata.EndArea.ToDomainValueObject(); + if (endAreaResult.IsFailure) + return endAreaResult.Errors; + + Result> aliasesResult = metadata.Aliases.ToDomainValueObjects(); + if (aliasesResult.IsFailure) + return aliasesResult.Errors; + Optional musicBrainzArtistId = Optional.None(); if (command.MusicBrainzArtistId is not null) musicBrainzArtistId = MusicBrainzId.Create(command.MusicBrainzArtistId.Value); - // The details and the media contributors of the artist are replaced in place, preserving its identity and creation metadata. - Result updateDetailsResult = artist.UpdateDetails(command.Name!, website, musicBrainzArtistId); + // The details and the media library collections of the artist are replaced in place, preserving its identity and creation metadata. + Result updateDetailsResult = artist.UpdateDetails( + metadata.Name!, + Optional.FromNullable(metadata.SortName), + Optional.FromNullable(metadata.Disambiguation), + Optional.FromNullable(metadata.Type), + Optional.FromNullable(metadata.Gender), + Optional.FromNullable(metadata.Country), + areaResult.Value, + beginAreaResult.Value, + endAreaResult.Value, + Optional.FromNullable(metadata.LifeSpanBegin), + Optional.FromNullable(metadata.LifeSpanEnd), + metadata.IsEnded, + Optional.FromNullable(command.Website), + musicBrainzArtistId); if (updateDetailsResult.IsFailure) return updateDetailsResult.Errors; + + artist.UpdateAliases(aliasesResult.Value); + artist.UpdateIpis([.. (command.Ipis ?? [])]); + artist.UpdateIsnis([.. (command.Isnis ?? [])]); + artist.UpdateGenres([.. domainGenresResult.Select(genreResult => genreResult.Value)]); + artist.UpdateTags([.. domainTagsResult.Select(tagResult => tagResult.Value)]); + artist.UpdateRatings([.. domainRatingsResult.Select(ratingResult => ratingResult.Value)]); artist.UpdateContributors([.. domainContributorsResult.Select(contributorResult => contributorResult.Value)]); List domainAlbums = [.. domainAlbumsResult.Select(albumResult => albumResult.Value)]; @@ -70,9 +127,14 @@ public static class UpdateArtistCommandMapping Result updateAlbumResult = artist.UpdateAlbum( existingAlbum, domainAlbum.Metadata, + domainAlbum.Disambiguation, domainAlbum.MediaFormat, + domainAlbum.Packaging, + domainAlbum.Script, domainAlbum.Barcode, - domainAlbum.CatalogNumber, + [.. domainAlbum.CatalogNumbers], + domainAlbum.Label, + domainAlbum.ASIN, domainAlbum.MusicBrainzReleaseId, domainAlbum.MusicBrainzReleaseGroupId, domainAlbum.MusicBrainzReleaseArtistId, @@ -103,10 +165,10 @@ public static class UpdateArtistCommandMapping domainTrack.Script, domainTrack.Key, domainTrack.Bpm, + domainTrack.IsVideo, domainTrack.Work, domainTrack.MusicBrainzRecordingId, domainTrack.MusicBrainzTrackId, - domainTrack.MusicBrainzWorkId, domainTrack.Moods, domainTrack.Isrcs, domainTrack.Contributors, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMapping.cs index 2671a203..ce2533c2 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMapping.cs @@ -23,10 +23,13 @@ public static class UpdateArtistRequestMapping return new UpdateArtistCommand( libraryId, artistId, - request.Name, + request.Metadata, request.Website, request.MusicBrainzArtistId, + request.Ipis, + request.Isnis, request.Contributors, + request.Ratings, request.Albums?.ToCommands(libraryId, artistId).ToList()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMapping.cs index ea80bc90..b7b5a02d 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMapping.cs @@ -36,7 +36,6 @@ public static class UpdateArtistTrackRequestMapping request.Work, request.MusicBrainzRecordingId, request.MusicBrainzTrackId, - request.MusicBrainzWorkId, request.Moods, request.Isrcs, request.Contributors, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/ArtistAliasEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/ArtistAliasEntityMapping.cs new file mode 100644 index 00000000..b9bc9148 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/ArtistAliasEntityMapping.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class ArtistAliasEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainValueObject(this ArtistAliasEntity repositoryEntity) + { + return MusicArtistAlias.Create( + repositoryEntity.Name, + Optional.FromNullable(repositoryEntity.SortName), + Optional.FromNullable(repositoryEntity.Type), + Optional.FromNullable(repositoryEntity.Locale), + repositoryEntity.IsPrimary, + Optional.FromNullable(repositoryEntity.BeginDate), + Optional.FromNullable(repositoryEntity.EndDate), + repositoryEntity.IsEnded); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// + /// An containing either the converted aliases, or an error message. + /// + public static Result> ToDomainValueObjects(this IEnumerable repositoryEntities) + { + List aliases = []; + foreach (ArtistAliasEntity repositoryEntity in repositoryEntities) + { + Result aliasResult = repositoryEntity.ToDomainValueObject(); + if (aliasResult.IsFailure) + return aliasResult.Errors; + aliases.Add(aliasResult.Value); + } + return aliases; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMapping.cs index c16bad24..5fc109a8 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMapping.cs @@ -21,7 +21,7 @@ public static class AudioRatingDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this AudioRatingDto dto) + public static Result ToDomainValueObject(this AudioRatingDto dto) { return AudioRating.Create( dto.Value ?? default, @@ -38,8 +38,8 @@ public static class AudioRatingDtoMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainValueObjects(this IEnumerable dtos) { - return dtos.Select(dto => dto.ToDomainEntity()); + return dtos.Select(dto => dto.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMapping.cs index 07dfa39c..0b0307c5 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMapping.cs @@ -47,7 +47,7 @@ public static class AudioRatingEntityMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this AudioRatingEntity repositoryEntity) + public static Result ToDomainValueObject(this AudioRatingEntity repositoryEntity) { return AudioRating.Create( repositoryEntity.Value ?? default, @@ -64,8 +64,8 @@ public static class AudioRatingEntityMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainValueObjects(this IEnumerable repositoryEntities) { - return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMapping.cs index ee7951b6..f9cc58ca 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMapping.cs @@ -20,7 +20,7 @@ public static class IsrcDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this IsrcDto dto) + public static Result ToDomainValueObject(this IsrcDto dto) { return Isrc.Create(dto.Value!); } @@ -32,8 +32,8 @@ public static class IsrcDtoMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainValueObjects(this IEnumerable dtos) { - return dtos.Select(dto => dto.ToDomainEntity()); + return dtos.Select(dto => dto.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMapping.cs index 4499e159..bbb8e77b 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMapping.cs @@ -43,7 +43,7 @@ public static class IsrcEntityMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this TrackIsrcEntity repositoryEntity) + public static Result ToDomainValueObject(this TrackIsrcEntity repositoryEntity) { return Isrc.Create(repositoryEntity.Value!); } @@ -55,8 +55,8 @@ public static class IsrcEntityMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainValueObjects(this IEnumerable repositoryEntities) { - return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMapping.cs index 661ec0ed..924278d9 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMapping.cs @@ -20,7 +20,7 @@ public static class MoodDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this MoodDto dto) + public static Result ToDomainValueObject(this MoodDto dto) { return Mood.Create(dto.Name!); } @@ -32,8 +32,8 @@ public static class MoodDtoMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainValueObjects(this IEnumerable dtos) { - return dtos.Select(dto => dto.ToDomainEntity()); + return dtos.Select(dto => dto.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMapping.cs index b70c86d3..92ee16f9 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMapping.cs @@ -43,7 +43,7 @@ public static class MoodEntityMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this TrackMoodEntity repositoryEntity) + public static Result ToDomainValueObject(this TrackMoodEntity repositoryEntity) { return Mood.Create(repositoryEntity.Name!); } @@ -55,8 +55,8 @@ public static class MoodEntityMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainValueObjects(this IEnumerable repositoryEntities) { - return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaDtoMapping.cs new file mode 100644 index 00000000..d4ee56c5 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaDtoMapping.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class MusicAreaDtoMapping +{ + /// + /// Converts to a domain , wrapped in an . + /// + /// The area data transfer object to be converted. + /// + /// An containing either the converted optional area, or an error message. + /// + public static Result> ToDomainValueObject(this MusicAreaDto? areaDto) + { + if (areaDto is null || areaDto.MusicBrainzAreaId is null) + return Optional.None(); + + Result areaResult = MusicArea.Create( + MusicBrainzId.Create(areaDto.MusicBrainzAreaId.Value), + areaDto.Name!, + Optional.FromNullable(areaDto.SortName), + Optional.FromNullable(areaDto.Disambiguation), + Optional.FromNullable(areaDto.Type), + Optional.FromNullable(areaDto.Iso3166Code)); + if (areaResult.IsFailure) + return areaResult.Errors; + return Optional.Some(areaResult.Value); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaEntityMapping.cs new file mode 100644 index 00000000..10a0a62e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaEntityMapping.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class MusicAreaEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainValueObject(this MusicAreaEntity repositoryEntity) + { + return MusicArea.Create( + MusicBrainzId.Create(repositoryEntity.MusicBrainzAreaId), + repositoryEntity.Name, + Optional.FromNullable(repositoryEntity.SortName), + Optional.FromNullable(repositoryEntity.Disambiguation), + Optional.FromNullable(repositoryEntity.Type), + Optional.FromNullable(repositoryEntity.Iso3166Code)); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted data transfer object, or when the repository entity is . + public static MusicAreaDto? ToResponse(this MusicAreaEntity? repositoryEntity) + { + return repositoryEntity is null + ? null + : new MusicAreaDto(repositoryEntity.MusicBrainzAreaId, repositoryEntity.Name, repositoryEntity.SortName, repositoryEntity.Disambiguation, repositoryEntity.Type, repositoryEntity.Iso3166Code); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaMapping.cs new file mode 100644 index 00000000..7814df4d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaMapping.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class MusicAreaMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static MusicAreaEntity ToRepositoryEntity(this MusicArea domainEntity) + { + return new MusicAreaEntity( + domainEntity.MusicBrainzAreaId.Value, + domainEntity.Name, + domainEntity.SortName.HasValue ? domainEntity.SortName.Value : null, + domainEntity.Disambiguation.HasValue ? domainEntity.Disambiguation.Value : null, + domainEntity.Type.HasValue ? domainEntity.Type.Value : null, + domainEntity.Iso3166Code.HasValue ? domainEntity.Iso3166Code.Value : null); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasDtoMapping.cs new file mode 100644 index 00000000..825945e1 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasDtoMapping.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class MusicArtistAliasDtoMapping +{ + /// + /// Converts to a domain . + /// + /// The alias data transfer object to be converted. + /// + /// An containing either the converted alias, or an error message. + /// + public static Result ToDomainValueObject(this MusicArtistAliasDto aliasDto) + { + return MusicArtistAlias.Create( + aliasDto.Name!, + Optional.FromNullable(aliasDto.SortName), + Optional.FromNullable(aliasDto.Type), + Optional.FromNullable(aliasDto.Locale), + aliasDto.IsPrimary, + Optional.FromNullable(aliasDto.BeginDate), + Optional.FromNullable(aliasDto.EndDate), + aliasDto.IsEnded); + } + + /// + /// Converts to a collection of domain . + /// + /// The alias data transfer objects to be converted. + /// + /// An containing either the converted aliases, or an error message. + /// + public static Result> ToDomainValueObjects(this IEnumerable? aliasDtos) + { + List aliases = []; + foreach (MusicArtistAliasDto aliasDto in aliasDtos ?? []) + { + Result aliasResult = aliasDto.ToDomainValueObject(); + if (aliasResult.IsFailure) + return aliasResult.Errors; + aliases.Add(aliasResult.Value); + } + return aliases; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasMapping.cs new file mode 100644 index 00000000..99b69b22 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasMapping.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class MusicArtistAliasMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static ArtistAliasEntity ToRepositoryEntity(this MusicArtistAlias domainEntity) + { + return new ArtistAliasEntity( + domainEntity.Name, + domainEntity.SortName.HasValue ? domainEntity.SortName.Value : null, + domainEntity.Type.HasValue ? domainEntity.Type.Value : null, + domainEntity.Locale.HasValue ? domainEntity.Locale.Value : null, + domainEntity.IsPrimary, + domainEntity.BeginDate.HasValue ? domainEntity.BeginDate.Value : null, + domainEntity.EndDate.HasValue ? domainEntity.EndDate.Value : null, + domainEntity.IsEnded); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted repository entities. + public static List ToRepositoryEntities(this IEnumerable domainEntities) + { + return [.. domainEntities.Select(domainEntity => domainEntity.ToRepositoryEntity())]; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMapping.cs index e609bdf1..11c15995 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMapping.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.Mapping.MediaContributors; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; @@ -29,39 +30,46 @@ public static class AddTrackCommandMapping /// public static Result ToDomainEntity(this AddTrackCommand command) { - Result metadataResult = command.Metadata!.ToDomainEntity(); + MusicTrackMetadataDto metadata = command.Metadata!; + Result metadataResult = metadata.ToDomainValueObject(); if (metadataResult.IsFailure) return metadataResult.Errors; - IEnumerable> domainMoodsResult = (command.Moods ?? []).ToDomainEntities(); + IEnumerable> domainMoodsResult = (command.Moods ?? []).ToDomainValueObjects(); List errors = [.. domainMoodsResult.Where(moodResult => moodResult.IsFailure).SelectMany(moodResult => moodResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainIsrcsResult = (command.Isrcs ?? []).ToDomainEntities(); + IEnumerable> domainIsrcsResult = (command.Isrcs ?? []).ToDomainValueObjects(); errors = [.. domainIsrcsResult.Where(isrcResult => isrcResult.IsFailure).SelectMany(isrcResult => isrcResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainContributorsResult = command.Contributors!.ToMusicDomainEntities(); + IEnumerable> domainContributorsResult = (command.Contributors ?? []).ToMusicDomainEntities(); errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + IEnumerable> domainRatingsResult = (command.Ratings ?? []).ToDomainValueObjects(); errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count > 0) return errors; + Optional work = Optional.None(); + if (command.Work is not null) + { + Result workResult = command.Work.ToDomainValueObject(); + if (workResult.IsFailure) + return workResult.Errors; + work = workResult.Value; + } + Optional musicBrainzRecordingId = Optional.None(); if (command.MusicBrainzRecordingId is not null) musicBrainzRecordingId = MusicBrainzId.Create(command.MusicBrainzRecordingId.Value); Optional musicBrainzTrackId = Optional.None(); if (command.MusicBrainzTrackId is not null) musicBrainzTrackId = MusicBrainzId.Create(command.MusicBrainzTrackId.Value); - Optional musicBrainzWorkId = Optional.None(); - if (command.MusicBrainzWorkId is not null) - musicBrainzWorkId = MusicBrainzId.Create(command.MusicBrainzWorkId.Value); List moods = [.. domainMoodsResult.Select(moodResult => moodResult.Value)]; List isrcs = [.. domainIsrcsResult.Select(isrcResult => isrcResult.Value)]; @@ -74,17 +82,18 @@ public static class AddTrackCommandMapping TrackId.Create(command.TrackId.Value), command.Path!, metadataResult.Value, + Optional.FromNullable(metadata.Disambiguation), command.TrackNumber!.Value, Optional.FromNullable(command.DiscNumber), moods, Optional.FromNullable(command.Script), Optional.FromNullable(command.Key), Optional.FromNullable(command.Bpm), + metadata.IsVideo, isrcs, - Optional.FromNullable(command.Work), + work, musicBrainzRecordingId, musicBrainzTrackId, - musicBrainzWorkId, contributors, ratings, DateTime.UtcNow, @@ -93,17 +102,18 @@ public static class AddTrackCommandMapping return Track.Create( command.Path!, metadataResult.Value, + Optional.FromNullable(metadata.Disambiguation), command.TrackNumber!.Value, Optional.FromNullable(command.DiscNumber), moods, Optional.FromNullable(command.Script), Optional.FromNullable(command.Key), Optional.FromNullable(command.Bpm), + metadata.IsVideo, isrcs, - Optional.FromNullable(command.Work), + work, musicBrainzRecordingId, musicBrainzTrackId, - musicBrainzWorkId, contributors, ratings); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMapping.cs index 9ada3803..8ad8b9de 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMapping.cs @@ -36,7 +36,6 @@ public static class AddTrackRequestMapping request.Work, request.MusicBrainzRecordingId, request.MusicBrainzTrackId, - request.MusicBrainzWorkId, request.Moods, request.Isrcs, request.Contributors, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs index 0642529c..c8c6da37 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs @@ -1,10 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; using System.Collections.Generic; @@ -18,65 +24,188 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibra public static class AudioMetadataDtoMapping { /// - /// Converts to a domain . + /// Applies the metadata of to , through the owning aggregate root. + /// + /// The audio metadata to apply. + /// The artist aggregate that owns the album of the track. + /// The album the track belongs to. + /// The track entity to update. + /// The media contributors of the track, already resolved to their persisted identifiers. + /// + /// An containing either the successfully updated , or an error message. + /// + public static Result ApplyTo(this AudioMetadataDto dto, Artist artist, Album album, Track track, IReadOnlyCollection contributors) + { + Result metadataResult = dto.ToDomainValueObject(track); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + List ratings = []; + foreach (AudioRatingDto rating in dto.Ratings ?? []) + { + Result ratingResult = rating.ToDomainValueObject(); + if (ratingResult.IsFailure) + return ratingResult.Errors; + ratings.Add(ratingResult.Value); + } + + // The work, the moods and the ISRCs of the track are only replaced when the provider returned values, so locally extracted data is never cleared. + Optional work = track.Work; + if (dto.Work is not null) + { + Result workResult = dto.Work.ToDomainValueObject(); + if (workResult.IsFailure) + return workResult.Errors; + work = workResult.Value; + } + + List moods = [.. track.Moods]; + if (dto.Moods is { Count: > 0 }) + { + moods = []; + foreach (MoodDto mood in dto.Moods) + { + Result moodResult = mood.ToDomainValueObject(); + if (moodResult.IsFailure) + return moodResult.Errors; + moods.Add(moodResult.Value); + } + } + + List isrcs = [.. track.Isrcs]; + if (dto.Isrcs is { Count: > 0 }) + { + isrcs = []; + foreach (IsrcDto isrc in dto.Isrcs) + { + Result isrcResult = isrc.ToDomainValueObject(); + if (isrcResult.IsFailure) + return isrcResult.Errors; + isrcs.Add(isrcResult.Value); + } + } + + Optional script = Optional.FromNullable(dto.Script); + if (!script.HasValue) + script = track.Script; + Optional key = Optional.FromNullable(dto.Key); + if (!key.HasValue) + key = track.Key; + Optional bpm = Optional.FromNullable(dto.Bpm); + if (!bpm.HasValue) + bpm = track.Bpm; + Optional musicBrainzRecordingId = Optional.None(); + if (dto.MusicBrainzRecordingId is not null) + musicBrainzRecordingId = MusicBrainzId.Create(dto.MusicBrainzRecordingId.Value); + else + musicBrainzRecordingId = track.MusicBrainzRecordingId; + Optional musicBrainzTrackId = Optional.None(); + if (dto.MusicBrainzTrackId is not null) + musicBrainzTrackId = MusicBrainzId.Create(dto.MusicBrainzTrackId.Value); + else + musicBrainzTrackId = track.MusicBrainzTrackId; + + return artist.UpdateTrackInAlbum( + album, + track, + track.Path, + metadataResult.Value, + track.TrackNumber, + track.DiscNumber, + script, + key, + bpm, + dto.IsVideo, + work, + musicBrainzRecordingId, + musicBrainzTrackId, + moods, + isrcs, + contributors, + ratings); + } + + /// + /// Converts to a domain , keeping the locally extracted audio properties that the provider did not return. /// /// The data transfer object to be converted. + /// The existing track whose locally extracted properties are preserved for the fields the provider left empty. /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this AudioMetadataDto dto) + private static Result ToDomainValueObject(this AudioMetadataDto dto, Track track) { - ReleaseInfoDto? releaseInfoDto = dto.ReleaseInfo; - Result releaseInfoResult = ReleaseInfo.Create( - Optional.FromNullable(releaseInfoDto?.OriginalReleaseDate), - Optional.FromNullable(releaseInfoDto?.OriginalReleaseYear), - Optional.FromNullable(releaseInfoDto?.ReReleaseDate), - Optional.FromNullable(releaseInfoDto?.ReReleaseYear), - Optional.FromNullable(releaseInfoDto?.ReleaseCountry), - Optional.FromNullable(releaseInfoDto?.ReleaseVersion)); + Result releaseInfoResult = dto.ReleaseInfo is null + ? ReleaseInfo.Create( + track.Metadata.ReleaseInfo.OriginalReleaseDate, + track.Metadata.ReleaseInfo.OriginalReleaseYear, + track.Metadata.ReleaseInfo.ReReleaseDate, + track.Metadata.ReleaseInfo.ReReleaseYear, + track.Metadata.ReleaseInfo.ReleaseCountry, + track.Metadata.ReleaseInfo.ReleaseVersion) + : ReleaseInfo.Create( + Optional.FromNullable(dto.ReleaseInfo.OriginalReleaseDate), + Optional.FromNullable(dto.ReleaseInfo.OriginalReleaseYear), + Optional.FromNullable(dto.ReleaseInfo.ReReleaseDate), + Optional.FromNullable(dto.ReleaseInfo.ReReleaseYear), + Optional.FromNullable(dto.ReleaseInfo.ReleaseCountry), + Optional.FromNullable(dto.ReleaseInfo.ReleaseVersion)); if (releaseInfoResult.IsFailure) return releaseInfoResult.Errors; - List domainGenres = []; - foreach (GenreDto genre in dto.Genres ?? []) + List genres = [.. track.Metadata.Genres]; + if (dto.Genres is { Count: > 0 }) { - Result genreResult = genre.ToDomainEntity(); - if (genreResult.IsFailure) - return genreResult.Errors; - domainGenres.Add(genreResult.Value); + genres = []; + foreach (GenreDto genre in dto.Genres) + { + Result genreResult = genre.ToDomainValueObject(); + if (genreResult.IsFailure) + return genreResult.Errors; + genres.Add(genreResult.Value); + } } - List domainTags = []; - foreach (TagDto tag in dto.Tags ?? []) + List tags = [.. track.Metadata.Tags]; + if (dto.Tags is { Count: > 0 }) { - Result tagResult = tag.ToDomainEntity(); - if (tagResult.IsFailure) - return tagResult.Errors; - domainTags.Add(tagResult.Value); + tags = []; + foreach (TagDto tag in dto.Tags) + { + Result tagResult = tag.ToDomainValueObject(); + if (tagResult.IsFailure) + return tagResult.Errors; + tags.Add(tagResult.Value); + } } - Optional language = Optional.None(); + Optional language = track.Metadata.Language; if (dto.Language is not null && dto.Language.LanguageCode is not null && dto.Language.LanguageName is not null) language = LanguageInfo.Create(dto.Language.LanguageCode, dto.Language.LanguageName, Optional.FromNullable(dto.Language.NativeName)); - Optional originalLanguage = Optional.None(); + Optional originalLanguage = track.Metadata.OriginalLanguage; 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.FromNullable(dto.OriginalLanguage.NativeName)); return AudioMetadata.Create( - dto.Title!, - Optional.FromNullable(dto.OriginalTitle), - dto.DurationInSeconds ?? 0, - dto.SampleRate ?? 0, - dto.Channels ?? 0, + string.IsNullOrWhiteSpace(dto.Title) ? track.Metadata.Title : dto.Title, + Optional.FromNullable(dto.OriginalTitle).HasValue ? Optional.FromNullable(dto.OriginalTitle) : track.Metadata.OriginalTitle, + dto.DurationInSeconds is > 0 ? dto.DurationInSeconds.Value : track.Metadata.DurationInSeconds, + dto.SampleRate is > 0 ? dto.SampleRate.Value : track.Metadata.SampleRate, + dto.Channels is > 0 ? dto.Channels.Value : track.Metadata.Channels, releaseInfoResult.Value, - Optional.FromNullable(dto.Description), - domainGenres, - domainTags, + Optional.FromNullable(dto.Description).HasValue ? Optional.FromNullable(dto.Description) : track.Metadata.Description, + genres, + tags, language, originalLanguage, - Optional.FromNullable(dto.BitDepth), - Optional.FromNullable(dto.AudioCodec), - Optional.FromNullable(dto.Bitrate)); + Optional.FromNullable(dto.BitDepth).HasValue ? Optional.FromNullable(dto.BitDepth) : track.Metadata.BitDepth, + Optional.FromNullable(dto.AudioCodec).HasValue ? Optional.FromNullable(dto.AudioCodec) : track.Metadata.AudioCodec, + Optional.FromNullable(dto.Bitrate).HasValue ? Optional.FromNullable(dto.Bitrate) : track.Metadata.Bitrate, + track.Metadata.AcoustId, + track.Metadata.ReplayGainTrackGain, + track.Metadata.ReplayGainTrackPeak, + track.Metadata.ReplayGainAlbumGain, + track.Metadata.ReplayGainAlbumPeak); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs new file mode 100644 index 00000000..4d05db8a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMapping.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class MusicTrackMetadataDtoMapping +{ + /// + /// Converts to a domain . + /// + /// The data transfer object to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainValueObject(this MusicTrackMetadataDto dto) + { + ReleaseInfoDto? releaseInfoDto = dto.ReleaseInfo; + Result releaseInfoResult = ReleaseInfo.Create( + Optional.FromNullable(releaseInfoDto?.OriginalReleaseDate), + Optional.FromNullable(releaseInfoDto?.OriginalReleaseYear), + Optional.FromNullable(releaseInfoDto?.ReReleaseDate), + Optional.FromNullable(releaseInfoDto?.ReReleaseYear), + Optional.FromNullable(releaseInfoDto?.ReleaseCountry), + Optional.FromNullable(releaseInfoDto?.ReleaseVersion)); + if (releaseInfoResult.IsFailure) + return releaseInfoResult.Errors; + + List domainGenres = []; + foreach (GenreDto genre in dto.Genres ?? []) + { + Result genreResult = genre.ToDomainValueObject(); + if (genreResult.IsFailure) + return genreResult.Errors; + domainGenres.Add(genreResult.Value); + } + + List domainTags = []; + foreach (TagDto tag in dto.Tags ?? []) + { + Result tagResult = tag.ToDomainValueObject(); + if (tagResult.IsFailure) + return tagResult.Errors; + domainTags.Add(tagResult.Value); + } + + Optional language = Optional.None(); + if (dto.Language is not null && dto.Language.LanguageCode is not null && dto.Language.LanguageName is not null) + language = LanguageInfo.Create(dto.Language.LanguageCode, dto.Language.LanguageName, Optional.FromNullable(dto.Language.NativeName)); + + Optional originalLanguage = Optional.None(); + 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.FromNullable(dto.OriginalLanguage.NativeName)); + + return AudioMetadata.Create( + dto.Title!, + Optional.FromNullable(dto.OriginalTitle), + dto.DurationInSeconds ?? 0, + dto.SampleRate ?? 0, + dto.Channels ?? 0, + releaseInfoResult.Value, + Optional.FromNullable(dto.Description), + domainGenres, + domainTags, + language, + originalLanguage, + Optional.FromNullable(dto.BitDepth), + Optional.FromNullable(dto.AudioCodec), + Optional.FromNullable(dto.Bitrate), + Optional.FromNullable(dto.AcoustId), + Optional.FromNullable(dto.ReplayGainTrackGain), + Optional.FromNullable(dto.ReplayGainTrackPeak), + Optional.FromNullable(dto.ReplayGainAlbumGain), + Optional.FromNullable(dto.ReplayGainAlbumPeak)); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicWorkDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicWorkDtoMapping.cs new file mode 100644 index 00000000..533ccc82 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicWorkDtoMapping.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class MusicWorkDtoMapping +{ + /// + /// Converts to a domain . + /// + /// The data transfer object to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainValueObject(this MusicWorkDto dto) + { + if (dto.MusicBrainzWorkId is null) + return Domain.Common.Errors.Errors.Music.MusicBrainzIdInvalidFormat; + if (string.IsNullOrWhiteSpace(dto.Title)) + return Domain.Common.Errors.Errors.Music.WorkTitleCannotBeEmpty; + + List languages = []; + foreach (LanguageInfoDto languageDto in dto.Languages ?? []) + { + if (string.IsNullOrWhiteSpace(languageDto.LanguageCode) || string.IsNullOrWhiteSpace(languageDto.LanguageName)) + continue; + languages.Add(LanguageInfo.Create(languageDto.LanguageCode, languageDto.LanguageName, Optional.FromNullable(languageDto.NativeName))); + } + + List iswcs = [.. (dto.Iswcs ?? []).Where(iswc => !string.IsNullOrWhiteSpace(iswc)).Select(iswc => iswc.Trim())]; + + return MusicWork.Create( + MusicBrainzId.Create(dto.MusicBrainzWorkId.Value), + dto.Title, + Optional.FromNullable(dto.Type), + languages, + iswcs); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs index 3689e5c8..82a08ab2 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs @@ -8,7 +8,6 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; @@ -48,7 +47,7 @@ public static class TrackEntityMapping return releaseInfoResult.Errors; List domainGenres = []; - foreach (Result genreResult in repositoryEntity.Genres.ToDomainEntities()) + foreach (Result genreResult in repositoryEntity.Genres.ToDomainValueObjects()) { if (genreResult.IsFailure) return genreResult.Errors; @@ -56,7 +55,7 @@ public static class TrackEntityMapping } List domainTags = []; - foreach (Result tagResult in repositoryEntity.Tags.ToDomainEntities()) + foreach (Result tagResult in repositoryEntity.Tags.ToDomainValueObjects()) { if (tagResult.IsFailure) return tagResult.Errors; @@ -85,7 +84,12 @@ public static class TrackEntityMapping originalLanguage, Optional.FromNullable(repositoryEntity.BitDepth), Optional.FromNullable(repositoryEntity.AudioCodec), - Optional.FromNullable(repositoryEntity.Bitrate)); + Optional.FromNullable(repositoryEntity.Bitrate), + Optional.FromNullable(repositoryEntity.AcoustId), + Optional.FromNullable(repositoryEntity.ReplayGainTrackGain), + Optional.FromNullable(repositoryEntity.ReplayGainTrackPeak), + Optional.FromNullable(repositoryEntity.ReplayGainAlbumGain), + Optional.FromNullable(repositoryEntity.ReplayGainAlbumPeak)); if (metadataResult.IsFailure) return metadataResult.Errors; @@ -95,12 +99,27 @@ public static class TrackEntityMapping Optional musicBrainzTrackId = Optional.None(); if (repositoryEntity.MusicBrainzTrackId is not null) musicBrainzTrackId = MusicBrainzId.Create(repositoryEntity.MusicBrainzTrackId.Value); - Optional musicBrainzWorkId = Optional.None(); - if (repositoryEntity.MusicBrainzWorkId is not null) - musicBrainzWorkId = MusicBrainzId.Create(repositoryEntity.MusicBrainzWorkId.Value); + + Optional work = Optional.None(); + if (repositoryEntity.MusicBrainzWorkId is not null && !string.IsNullOrWhiteSpace(repositoryEntity.WorkTitle)) + { + List workLanguages = []; + foreach (TrackWorkLanguageEntity workLanguage in repositoryEntity.WorkLanguages) + workLanguages.Add(LanguageInfo.Create(workLanguage.LanguageCode, workLanguage.LanguageName, Optional.FromNullable(workLanguage.NativeName))); + + Result workResult = MusicWork.Create( + MusicBrainzId.Create(repositoryEntity.MusicBrainzWorkId.Value), + repositoryEntity.WorkTitle, + Optional.FromNullable(repositoryEntity.WorkType), + workLanguages, + [.. repositoryEntity.WorkIswcs.Select(workIswc => workIswc.Value)]); + if (workResult.IsFailure) + return workResult.Errors; + work = workResult.Value; + } List domainMoods = []; - foreach (Result moodResult in repositoryEntity.Moods.ToDomainEntities()) + foreach (Result moodResult in repositoryEntity.Moods.ToDomainValueObjects()) { if (moodResult.IsFailure) return moodResult.Errors; @@ -108,7 +127,7 @@ public static class TrackEntityMapping } List domainIsrcs = []; - foreach (Result isrcResult in repositoryEntity.Isrcs.ToDomainEntities()) + foreach (Result isrcResult in repositoryEntity.Isrcs.ToDomainValueObjects()) { if (isrcResult.IsFailure) return isrcResult.Errors; @@ -116,7 +135,7 @@ public static class TrackEntityMapping } List domainRatings = []; - foreach (Result ratingResult in repositoryEntity.Ratings.ToDomainEntities()) + foreach (Result ratingResult in repositoryEntity.Ratings.ToDomainValueObjects()) { if (ratingResult.IsFailure) return ratingResult.Errors; @@ -136,17 +155,18 @@ public static class TrackEntityMapping TrackId.Create(repositoryEntity.Id), repositoryEntity.Path, metadataResult.Value, + Optional.FromNullable(repositoryEntity.Disambiguation), repositoryEntity.TrackNumber, Optional.FromNullable(repositoryEntity.DiscNumber), domainMoods, Optional.FromNullable(repositoryEntity.Script), Optional.FromNullable(repositoryEntity.Key), Optional.FromNullable(repositoryEntity.Bpm), + repositoryEntity.IsVideo, domainIsrcs, - Optional.FromNullable(repositoryEntity.Work), + work, musicBrainzRecordingId, musicBrainzTrackId, - musicBrainzWorkId, domainContributors, domainRatings, repositoryEntity.CreatedOnUtc, @@ -185,21 +205,40 @@ public static class TrackEntityMapping repositoryEntity.OriginalLanguageName, repositoryEntity.OriginalLanguageNativeName ) : null; - AudioMetadataDto metadata = new( + MusicWorkDto? work = null; + if (repositoryEntity.MusicBrainzWorkId is not null && !string.IsNullOrWhiteSpace(repositoryEntity.WorkTitle)) + work = new MusicWorkDto( + repositoryEntity.MusicBrainzWorkId, + repositoryEntity.WorkTitle, + repositoryEntity.WorkType, + repositoryEntity.WorkLanguages.Count > 0 + ? [.. repositoryEntity.WorkLanguages.Select(workLanguage => new LanguageInfoDto(workLanguage.LanguageCode, workLanguage.LanguageName, workLanguage.NativeName))] + : null, + repositoryEntity.WorkIswcs.Count > 0 + ? [.. repositoryEntity.WorkIswcs.Select(workIswc => workIswc.Value)] + : null); + MusicTrackMetadataDto metadata = new( repositoryEntity.Title, repositoryEntity.OriginalTitle, repositoryEntity.Description, + repositoryEntity.Disambiguation, releaseInfo, languageInfo, originalLanguageInfo, [.. repositoryEntity.Tags.ToResponses()], [.. repositoryEntity.Genres.ToResponses()], + repositoryEntity.IsVideo, repositoryEntity.DurationInSeconds, repositoryEntity.SampleRate, repositoryEntity.Channels, repositoryEntity.BitDepth, repositoryEntity.AudioCodec, - repositoryEntity.Bitrate + repositoryEntity.Bitrate, + repositoryEntity.AcoustId, + repositoryEntity.ReplayGainTrackGain, + repositoryEntity.ReplayGainTrackPeak, + repositoryEntity.ReplayGainAlbumGain, + repositoryEntity.ReplayGainAlbumPeak ); return new TrackResponse( repositoryEntity.Id, @@ -212,10 +251,9 @@ public static class TrackEntityMapping repositoryEntity.Script, repositoryEntity.Key, repositoryEntity.Bpm, - repositoryEntity.Work, + work, repositoryEntity.MusicBrainzRecordingId, repositoryEntity.MusicBrainzTrackId, - repositoryEntity.MusicBrainzWorkId, repositoryEntity.CreatedOnUtc, repositoryEntity.UpdatedOnUtc, [.. repositoryEntity.Moods.ToResponses()], diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs index 087d386a..c666917c 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs @@ -5,7 +5,6 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibrary using System; using System.Linq; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; - #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; @@ -33,6 +32,7 @@ public static class TrackMapping Title = domainEntity.Metadata.Title, OriginalTitle = domainEntity.Metadata.OriginalTitle.HasValue ? domainEntity.Metadata.OriginalTitle.Value : null, Description = domainEntity.Metadata.Description.HasValue ? domainEntity.Metadata.Description.Value : null, + Disambiguation = domainEntity.Disambiguation.HasValue ? domainEntity.Disambiguation.Value : null, OriginalReleaseDate = domainEntity.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? domainEntity.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null, OriginalReleaseYear = domainEntity.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? domainEntity.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null, ReReleaseDate = domainEntity.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? domainEntity.Metadata.ReleaseInfo.ReReleaseDate.Value : null, @@ -53,15 +53,22 @@ public static class TrackMapping BitDepth = domainEntity.Metadata.BitDepth.HasValue ? domainEntity.Metadata.BitDepth.Value : null, AudioCodec = domainEntity.Metadata.AudioCodec.HasValue ? domainEntity.Metadata.AudioCodec.Value : null, Bitrate = domainEntity.Metadata.Bitrate.HasValue ? domainEntity.Metadata.Bitrate.Value : null, + AcoustId = domainEntity.Metadata.AcoustId.HasValue ? domainEntity.Metadata.AcoustId.Value : null, + ReplayGainTrackGain = domainEntity.Metadata.ReplayGainTrackGain.HasValue ? domainEntity.Metadata.ReplayGainTrackGain.Value : null, + ReplayGainTrackPeak = domainEntity.Metadata.ReplayGainTrackPeak.HasValue ? domainEntity.Metadata.ReplayGainTrackPeak.Value : null, + ReplayGainAlbumGain = domainEntity.Metadata.ReplayGainAlbumGain.HasValue ? domainEntity.Metadata.ReplayGainAlbumGain.Value : null, + ReplayGainAlbumPeak = domainEntity.Metadata.ReplayGainAlbumPeak.HasValue ? domainEntity.Metadata.ReplayGainAlbumPeak.Value : null, TrackNumber = domainEntity.TrackNumber, DiscNumber = domainEntity.DiscNumber.HasValue ? domainEntity.DiscNumber.Value : null, Script = domainEntity.Script.HasValue ? domainEntity.Script.Value : null, Key = domainEntity.Key.HasValue ? domainEntity.Key.Value : null, Bpm = domainEntity.Bpm.HasValue ? domainEntity.Bpm.Value : null, - Work = domainEntity.Work.HasValue ? domainEntity.Work.Value : null, + IsVideo = domainEntity.IsVideo, + WorkTitle = domainEntity.Work.HasValue ? domainEntity.Work.Value.Title : null, + WorkType = domainEntity.Work.HasValue && domainEntity.Work.Value.Type.HasValue ? domainEntity.Work.Value.Type.Value : null, MusicBrainzRecordingId = domainEntity.MusicBrainzRecordingId.HasValue ? domainEntity.MusicBrainzRecordingId.Value.Value : null, MusicBrainzTrackId = domainEntity.MusicBrainzTrackId.HasValue ? domainEntity.MusicBrainzTrackId.Value.Value : null, - MusicBrainzWorkId = domainEntity.MusicBrainzWorkId.HasValue ? domainEntity.MusicBrainzWorkId.Value.Value : null, + MusicBrainzWorkId = domainEntity.Work.HasValue ? domainEntity.Work.Value.MusicBrainzWorkId.Value : null, Contributors = [.. domainEntity.Contributors.Select(contributor => new TrackContributorEntity { Id = Guid.NewGuid(), @@ -74,6 +81,12 @@ public static class TrackMapping })], Moods = [.. domainEntity.Moods.ToRepositoryEntities()], Isrcs = [.. domainEntity.Isrcs.ToRepositoryEntities()], + WorkLanguages = domainEntity.Work.HasValue + ? [.. domainEntity.Work.Value.Languages.Select(language => new TrackWorkLanguageEntity(language.LanguageCode, language.LanguageName, language.NativeName.HasValue ? language.NativeName.Value : null))] + : [], + WorkIswcs = domainEntity.Work.HasValue + ? [.. domainEntity.Work.Value.Iswcs.Select(iswc => new TrackWorkIswcEntity(iswc))] + : [], Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], CreatedOnUtc = domainEntity.CreatedOnUtc, CreatedBy = Guid.Empty, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs index ee4d7bda..143a6ba9 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.Mapping.MediaContributors; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; @@ -32,39 +33,46 @@ public static class UpdateTrackCommandMapping /// public static Result ToDomainEntity(this UpdateTrackCommand command, Artist artist) { - Result metadataResult = command.Metadata!.ToDomainEntity(); + MusicTrackMetadataDto metadata = command.Metadata!; + Result metadataResult = metadata.ToDomainValueObject(); if (metadataResult.IsFailure) return metadataResult.Errors; - IEnumerable> domainMoodsResult = (command.Moods ?? []).ToDomainEntities(); + IEnumerable> domainMoodsResult = (command.Moods ?? []).ToDomainValueObjects(); List errors = [.. domainMoodsResult.Where(moodResult => moodResult.IsFailure).SelectMany(moodResult => moodResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainIsrcsResult = (command.Isrcs ?? []).ToDomainEntities(); + IEnumerable> domainIsrcsResult = (command.Isrcs ?? []).ToDomainValueObjects(); errors = [.. domainIsrcsResult.Where(isrcResult => isrcResult.IsFailure).SelectMany(isrcResult => isrcResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainContributorsResult = command.Contributors!.ToMusicDomainEntities(); + IEnumerable> domainContributorsResult = (command.Contributors ?? []).ToMusicDomainEntities(); errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + IEnumerable> domainRatingsResult = (command.Ratings ?? []).ToDomainValueObjects(); errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count > 0) return errors; + Optional work = Optional.None(); + if (command.Work is not null) + { + Result workResult = command.Work.ToDomainValueObject(); + if (workResult.IsFailure) + return workResult.Errors; + work = workResult.Value; + } + Optional musicBrainzRecordingId = Optional.None(); if (command.MusicBrainzRecordingId is not null) musicBrainzRecordingId = MusicBrainzId.Create(command.MusicBrainzRecordingId.Value); Optional musicBrainzTrackId = Optional.None(); if (command.MusicBrainzTrackId is not null) musicBrainzTrackId = MusicBrainzId.Create(command.MusicBrainzTrackId.Value); - Optional musicBrainzWorkId = Optional.None(); - if (command.MusicBrainzWorkId is not null) - musicBrainzWorkId = MusicBrainzId.Create(command.MusicBrainzWorkId.Value); // The album and the track are entities inside the artist aggregate, so they are referenced by object, not by id; the aggregate members are located here and passed through. Album? album = artist.Albums.FirstOrDefault(album => album.Id.Value == Guid.Parse(command.AlbumId!)); @@ -84,10 +92,10 @@ public static class UpdateTrackCommandMapping Optional.FromNullable(command.Script), Optional.FromNullable(command.Key), Optional.FromNullable(command.Bpm), - Optional.FromNullable(command.Work), + metadata.IsVideo, + work, musicBrainzRecordingId, musicBrainzTrackId, - musicBrainzWorkId, [.. domainMoodsResult.Select(moodResult => moodResult.Value)], [.. domainIsrcsResult.Select(isrcResult => isrcResult.Value)], [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)], diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs index 3635ccf8..257e2bf1 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs @@ -36,7 +36,6 @@ public static class UpdateTrackRequestMapping request.Work, request.MusicBrainzRecordingId, request.MusicBrainzTrackId, - request.MusicBrainzWorkId, request.Moods, request.Isrcs, request.Contributors, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs index f524961e..e02402e7 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Linq; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; @@ -26,7 +28,8 @@ public static class AddMediaLibraryRequestMapping request.IsLocked, request.CanDownloadMetadataFromWeb, request.ShouldSaveMetadataInMediaDirectories, - request.ShouldSkipUnchangedDirectoriesDuringScan + request.ShouldSkipUnchangedDirectoriesDuringScan, + request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray() ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMapping.cs new file mode 100644 index 00000000..b407fb7a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; +using Lumina.Contracts.Requests.MediaLibrary.Management; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryPathTemplatePartsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryPathTemplatePartsQuery ToQuery(this GetLibraryPathTemplatePartsRequest request) + { + return new GetLibraryPathTemplatePartsQuery( + request.LibraryType + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index 2e7e8142..70060f17 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -36,6 +36,9 @@ public static class LibraryEntityMapping repositoryEntity.CanDownloadMetadataFromWeb, repositoryEntity.ShouldSaveMetadataInMediaDirectories, repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan, + [.. repositoryEntity.PathTemplateParts + .OrderBy(part => part.Position) + .Select(part => new LibraryPathTemplatePartResponse(part.Kind.ToString(), part.Representation, part.IsOptional))], repositoryEntity.CreatedOnUtc, repositoryEntity.UpdatedOnUtc ); @@ -50,6 +53,10 @@ public static class LibraryEntityMapping /// public static Result ToDomainEntity(this LibraryEntity repositoryEntity) { + Result pathTemplateResult = BuildPathTemplate(repositoryEntity.PathTemplateParts); + if (pathTemplateResult.IsFailure) + return pathTemplateResult.Errors; + return Library.Create( LibraryId.Create(repositoryEntity.Id), UserId.Create(repositoryEntity.UserId), @@ -62,10 +69,31 @@ public static class LibraryEntityMapping repositoryEntity.CanDownloadMetadataFromWeb, repositoryEntity.ShouldSaveMetadataInMediaDirectories, repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan, + pathTemplateResult.Value, [.. repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))] ); } + /// + /// Builds the path template of a media library from its ordered stored parts. + /// + /// The stored parts of the path template. + /// + /// An containing either the built , or an error message. + /// + private static Result BuildPathTemplate(IEnumerable parts) + { + List orderedParts = []; + foreach (LibraryPathTemplatePartEntity part in parts.OrderBy(part => part.Position)) + { + Result partResult = LibraryPathPart.Create(part.Kind, part.Representation, part.IsOptional); + if (partResult.IsFailure) + return partResult.Errors; + orderedParts.Add(partResult.Value); + } + return LibraryPathTemplate.Create(orderedParts); + } + /// /// Converts to a collection of . /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs index be721acb..3d90a2a8 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs @@ -26,6 +26,13 @@ public static class LibraryMapping LibraryType = domainEntity.LibraryType, UserId = domainEntity.UserId.Value, ContentLocations = [.. domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path })], + PathTemplateParts = [.. domainEntity.PathTemplate.Parts.Select((part, index) => new LibraryPathTemplatePartEntity + { + Kind = part.Kind, + Representation = part.Representation, + IsOptional = part.IsOptional, + Position = index + })], CoverImage = domainEntity.CoverImage.HasValue ? domainEntity.CoverImage.Value : null, IsEnabled = domainEntity.IsEnabled, IsLocked = domainEntity.IsLocked, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMapping.cs new file mode 100644 index 00000000..df2c4165 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMapping.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class LibraryPathTemplatePartDtoMapping +{ + /// + /// Converts the provided path template parts to their domain path parts. + /// + /// The path template parts to be converted. + /// + /// An containing either the converted domain path parts, or an error message. + /// + public static Result> ToDomainParts(this IEnumerable? parts) + { + List domainParts = []; + if (parts is null) + return domainParts; + + foreach (LibraryPathTemplatePartDto part in parts) + { + if (!Enum.TryParse(part.Kind, ignoreCase: true, out LibraryPathPartKind kind)) + return DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType; + + Result partResult = LibraryPathPart.Create(kind, part.Representation, part.IsOptional); + if (partResult.IsFailure) + return partResult.Errors; + + domainParts.Add(partResult.Value); + } + return domainParts; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs index 374f9e15..529bbc32 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Linq; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; @@ -28,7 +30,8 @@ public static class UpdateLibraryRequestMapping request.IsLocked, request.CanDownloadMetadataFromWeb, request.ShouldSaveMetadataInMediaDirectories, - request.ShouldSkipUnchangedDirectoriesDuringScan + request.ShouldSkipUnchangedDirectoriesDuringScan, + request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray() ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs index ba89c298..36c4c94f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs @@ -32,17 +32,17 @@ public static class AddBookCommandMapping /// public static Result ToDomainEntity(this AddBookCommand command, Guid libraryId) { - IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + IEnumerable> domainRatingsResult = command.Ratings!.ToDomainValueObjects(); List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainIsbnsResult = command.ISBNs!.ToDomainEntities(); + IEnumerable> domainIsbnsResult = command.ISBNs!.ToDomainValueObjects(); errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; if (errors.Count > 0) return errors; - Result metadataResult = command.Metadata!.ToDomainEntity(); + Result metadataResult = command.Metadata!.ToDomainValueObject(); if (metadataResult.IsFailure) return metadataResult.Errors; diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index a143e43e..f5475a89 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -40,22 +40,22 @@ public static class BookEntityMapping /// public static Result ToDomainEntity(this BookEntity repositoryEntity) { - IEnumerable> tagsResult = repositoryEntity.Tags.ToDomainEntities(); + IEnumerable> tagsResult = repositoryEntity.Tags.ToDomainValueObjects(); foreach (Result tagResult in tagsResult) if (tagResult.IsFailure) return tagResult.Errors; - IEnumerable> genresResult = repositoryEntity.Genres.ToDomainEntities(); + IEnumerable> genresResult = repositoryEntity.Genres.ToDomainValueObjects(); foreach (Result genreResult in genresResult) if (genreResult.IsFailure) return genreResult.Errors; - IEnumerable> isbnsResult = repositoryEntity.ISBNs.ToDomainEntities(); + IEnumerable> isbnsResult = repositoryEntity.ISBNs.ToDomainValueObjects(); foreach (Result isbnResult in isbnsResult) if (isbnResult.IsFailure) return isbnResult.Errors; - IEnumerable> bookRatingsResult = repositoryEntity.Ratings.ToDomainEntities(); + IEnumerable> bookRatingsResult = repositoryEntity.Ratings.ToDomainValueObjects(); foreach (Result bookRatingResult in bookRatingsResult) if (bookRatingResult.IsFailure) return bookRatingResult.Errors; diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs index 40e63a13..b3c5101f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs @@ -33,17 +33,17 @@ public static class UpdateBookCommandMapping /// public static Result ToDomainEntity(this UpdateBookCommand command, BookEntity existingBook) { - IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + IEnumerable> domainRatingsResult = command.Ratings!.ToDomainValueObjects(); List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainIsbnsResult = command.ISBNs!.ToDomainEntities(); + IEnumerable> domainIsbnsResult = command.ISBNs!.ToDomainValueObjects(); errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; if (errors.Count > 0) return errors; - Result metadataResult = command.Metadata!.ToDomainEntity(); + Result metadataResult = command.Metadata!.ToDomainValueObject(); if (metadataResult.IsFailure) return metadataResult.Errors; diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs index 9f9c6e3c..2af5248c 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMapping.cs @@ -22,7 +22,7 @@ public static class BookRatingDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this BookRatingDto dto) + public static Result ToDomainValueObject(this BookRatingDto dto) { return BookRating.Create( dto.Value ?? default, @@ -39,8 +39,8 @@ public static class BookRatingDtoMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainValueObjects(this IEnumerable dtos) { - return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); + return dtos.Select(domainEntity => domainEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs index f8406648..8718cc57 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMapping.cs @@ -48,7 +48,7 @@ public static class BookRatingEntityMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this BookRatingEntity repositoryEntity) + public static Result ToDomainValueObject(this BookRatingEntity repositoryEntity) { return BookRating.Create( repositoryEntity.Value ?? default, @@ -65,8 +65,8 @@ public static class BookRatingEntityMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainValueObjects(this IEnumerable repositoryEntities) { - return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs index 359effde..01eaed1b 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMapping.cs @@ -21,7 +21,7 @@ public static class IsbnDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this IsbnDto dto) + public static Result ToDomainValueObject(this IsbnDto dto) { return Isbn.Create( dto.Value!, @@ -36,8 +36,8 @@ public static class IsbnDtoMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + public static IEnumerable> ToDomainValueObjects(this IEnumerable dtos) { - return dtos.Select(domainEntity => domainEntity.ToDomainEntity()); + return dtos.Select(domainEntity => domainEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs index f4998385..4095338e 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMapping.cs @@ -44,7 +44,7 @@ public static class IsbnEntityMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this IsbnEntity repositoryEntity) + public static Result ToDomainValueObject(this IsbnEntity repositoryEntity) { return Isbn.Create( repositoryEntity.Value!, @@ -59,8 +59,8 @@ public static class IsbnEntityMapping /// /// An containing either a collection of converted , or an error message. /// - public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + public static IEnumerable> ToDomainValueObjects(this IEnumerable repositoryEntities) { - return repositoryEntities.Select(domainEntity => domainEntity.ToDomainEntity()); + return repositoryEntities.Select(domainEntity => domainEntity.ToDomainValueObject()); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs index 931e66c5..a2a88fb8 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs @@ -22,28 +22,28 @@ public static class WrittenContentMetadataDtoMapping /// /// An containing either a successfully converted , or an error message. /// - public static Result ToDomainEntity(this WrittenContentMetadataDto dto) + public static Result ToDomainValueObject(this WrittenContentMetadataDto dto) { - Result? domainReleaseInfoResult = dto.ReleaseInfo!.ToDomainEntity(); + Result? domainReleaseInfoResult = dto.ReleaseInfo!.ToDomainValueObject(); if (domainReleaseInfoResult.Value.IsFailure) return domainReleaseInfoResult.Value.Errors; - IEnumerable> domainGenresResult = dto.Genres!.ToDomainEntities(); + IEnumerable> domainGenresResult = dto.Genres!.ToDomainValueObjects(); List errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; if (errors.Count > 0) return errors; - IEnumerable> domainTagsResult = dto.Tags!.ToDomainEntities(); + IEnumerable> domainTagsResult = dto.Tags!.ToDomainValueObjects(); errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; if (errors.Count > 0) return errors; - Result? domainLanguageInfoResult = dto.Language?.ToDomainEntity(); + Result? domainLanguageInfoResult = dto.Language?.ToDomainValueObject(); if (domainLanguageInfoResult.HasValue && domainLanguageInfoResult.Value.IsFailure) return domainLanguageInfoResult.Value.Errors; - Result? domainOriginalLanguageInfoResult = dto.OriginalLanguage?.ToDomainEntity(); + Result? domainOriginalLanguageInfoResult = dto.OriginalLanguage?.ToDomainValueObject(); if (domainOriginalLanguageInfoResult.HasValue && domainOriginalLanguageInfoResult.Value.IsFailure) return domainOriginalLanguageInfoResult.Value.Errors; diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs index e4c9c955..a936d1b2 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs @@ -23,6 +23,7 @@ public static class UpdateUserSettingsRequestMapping request.ShouldIgnoreThePrefixForAlphaPicker, request.IsThemeCachingEnabled, request.ShouldAggregateMetadataWhenMissing, + request.ShouldAggregateArtworkWhenMissing, request.ShouldRenderPdfAsImages, request.ShouldPreserveBookStyles ); diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs index f556846c..4da52a6f 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs @@ -31,6 +31,7 @@ public static class UserSettingsEntityMapping repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker, repositoryEntity.IsThemeCachingEnabled, repositoryEntity.ShouldAggregateMetadataWhenMissing, + repositoryEntity.ShouldAggregateArtworkWhenMissing, repositoryEntity.ShouldRenderPdfAsImages, repositoryEntity.ShouldPreserveBookStyles ); @@ -50,6 +51,7 @@ public static class UserSettingsEntityMapping repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker, repositoryEntity.IsThemeCachingEnabled, repositoryEntity.ShouldAggregateMetadataWhenMissing, + repositoryEntity.ShouldAggregateArtworkWhenMissing, repositoryEntity.ShouldRenderPdfAsImages, repositoryEntity.ShouldPreserveBookStyles ); diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs index 01c0e99a..aabba107 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs @@ -27,6 +27,7 @@ public static class UserSettingsMapping ShouldIgnoreThePrefixForAlphaPicker = domainEntity.ShouldIgnoreThePrefixForAlphaPicker, IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled, ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing, + ShouldAggregateArtworkWhenMissing = domainEntity.ShouldAggregateArtworkWhenMissing, ShouldRenderPdfAsImages = domainEntity.ShouldRenderPdfAsImages, ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles }; @@ -46,6 +47,7 @@ public static class UserSettingsMapping domainEntity.ShouldIgnoreThePrefixForAlphaPicker, domainEntity.IsThemeCachingEnabled, domainEntity.ShouldAggregateMetadataWhenMissing, + domainEntity.ShouldAggregateArtworkWhenMissing, domainEntity.ShouldRenderPdfAsImages, domainEntity.ShouldPreserveBookStyles ); diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommand.cs index 8a0a0f38..bef552ec 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommand.cs @@ -19,22 +19,29 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums. /// The Id of the artist the album belongs to, taken from the route. /// The album metadata of the album. /// The physical or digital medium of the album, if applicable. +/// The outermost physical packaging of the album, if applicable. /// The barcode of the album, if applicable. -/// The catalog number of the album, if applicable. +/// The catalog numbers of the album, if applicable. +/// The name of the label that issued the album, if applicable. +/// The ASIN (Amazon Standard Identification Number) of the album, if applicable. /// The MusicBrainz identifier of the release, if applicable. /// The MusicBrainz identifier of the release group, if applicable. /// The MusicBrainz identifier of the release artist, if applicable. /// The list of media contributors that performed on the album. /// The list of ratings for this album. /// The list of tracks of the album. +/// The Id of the album, when the album already exists. [DebuggerDisplay("Title: {Metadata.Title}")] public record AddAlbumCommand( string? LibraryId, string? ArtistId, - AlbumMetadataDto? Metadata, + MusicAlbumMetadataDto? Metadata, MusicMediaFormat? MediaFormat, + MusicReleasePackaging? Packaging, string? Barcode, - string? CatalogNumber, + List? CatalogNumbers, + string? Label, + string? ASIN, Guid? MusicBrainzReleaseId, Guid? MusicBrainzReleaseGroupId, Guid? MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidator.cs index 9dc0f385..7f8a4636 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidator.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using System; +using System.Linq; #endregion namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; @@ -37,7 +38,7 @@ public class AddAlbumCommandValidator : AbstractValidator .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) .WithError(Errors.Music.ArtistIdCannotBeEmpty); - // Validates the metadata of the album: title, lengths, release type and status, disc and track counts, release information, languages, genres and tags. + // Validates the metadata of the album: title, lengths, release types and status, disc and track counts, release information, languages, genres and tags. RuleFor(command => command.Metadata) .NotNull() .WithError(Errors.Metadata.MetadataCannotBeNull) @@ -60,9 +61,13 @@ public class AddAlbumCommandValidator : AbstractValidator .When(m => m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); - metadata.RuleFor(m => m!.ReleaseType) + metadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleForEach(m => m!.ReleaseTypes) .IsInEnum() - .When(m => m!.ReleaseType is not null) .WithError(Errors.Music.UnknownMusicReleaseType); metadata.RuleFor(m => m!.ReleaseStatus) @@ -196,15 +201,20 @@ public class AddAlbumCommandValidator : AbstractValidator .When(m => m!.OriginalLanguage is not null); }); - // Validates the physical characteristics of the album: format and catalog number. + // Validates the physical characteristics of the album: format, packaging, catalog number and barcode. RuleFor(command => command.MediaFormat) .IsInEnum() .When(command => command.MediaFormat is not null) .WithError(Errors.Music.UnknownMusicMediaFormat); - RuleFor(command => command.CatalogNumber) + RuleFor(command => command.Packaging) + .IsInEnum() + .When(command => command.Packaging is not null) + .WithError(Errors.Music.UnknownMusicReleasePackaging); + + RuleForEach(command => command.CatalogNumbers) .MaximumLength(50) - .When(command => command.CatalogNumber is not null) + .When(command => command.CatalogNumbers is not null) .WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); RuleFor(command => command.Barcode) @@ -313,6 +323,11 @@ public class AddAlbumCommandValidator : AbstractValidator .When(m => m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.ReleaseInfo) .NotNull() .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) @@ -440,11 +455,6 @@ public class AddAlbumCommandValidator : AbstractValidator .When(t => t!.MusicBrainzTrackId.HasValue) .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - track.RuleFor(t => t!.MusicBrainzWorkId) - .Must(musicBrainzWorkId => musicBrainzWorkId != Guid.Empty) - .When(t => t!.MusicBrainzWorkId.HasValue) - .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - // Validates the ordering and performance characteristics of the track. track.RuleFor(t => t!.TrackNumber) .NotNull() @@ -475,11 +485,17 @@ public class AddAlbumCommandValidator : AbstractValidator .When(t => t!.Bpm.HasValue) .WithError(Errors.Music.BpmMustBeGreaterThanZero); - track.RuleFor(t => t!.Work) + // Validates the work the track is a recording of. + track.RuleFor(t => t!.Work!.Title) .MaximumLength(255) - .When(t => t!.Work is not null) + .When(t => t!.Work is not null && t.Work.Title is not null) .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + track.RuleFor(t => t!.Work!.MusicBrainzWorkId) + .Must(musicBrainzWorkId => musicBrainzWorkId is null || musicBrainzWorkId != Guid.Empty) + .When(t => t!.Work is not null) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + // Validates the media contributors that performed on the track. track.RuleFor(t => t!.Contributors) .NotNull() diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommand.cs index d31323ff..515bc6ca 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommand.cs @@ -19,8 +19,11 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums. /// The unique identifier of the album, taken from the route. /// The album metadata of the album. /// The physical or digital medium of the album, if applicable. +/// The outermost physical packaging of the album, if applicable. /// The barcode of the album, if applicable. -/// The catalog number of the album, if applicable. +/// The catalog numbers of the album, if applicable. +/// The name of the label that issued the album, if applicable. +/// The ASIN (Amazon Standard Identification Number) of the album, if applicable. /// The MusicBrainz identifier of the release, if applicable. /// The MusicBrainz identifier of the release group, if applicable. /// The MusicBrainz identifier of the release artist, if applicable. @@ -31,10 +34,13 @@ public record UpdateAlbumCommand( string? LibraryId, string? ArtistId, string? AlbumId, - AlbumMetadataDto? Metadata, + MusicAlbumMetadataDto? Metadata, MusicMediaFormat? MediaFormat, + MusicReleasePackaging? Packaging, string? Barcode, - string? CatalogNumber, + List? CatalogNumbers, + string? Label, + string? ASIN, Guid? MusicBrainzReleaseId, Guid? MusicBrainzReleaseGroupId, Guid? MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidator.cs index 48fa09ff..2247cdc7 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidator.cs @@ -47,7 +47,7 @@ public class UpdateAlbumCommandValidator : AbstractValidator .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) .WithError(Errors.Music.AlbumIdCannotBeEmpty); - // Validates the metadata of the album: title, lengths, release type and status, disc and track counts, release information, languages, genres and tags. + // Validates the metadata of the album: title, lengths, release types and status, disc and track counts, release information, languages, genres and tags. RuleFor(command => command.Metadata) .NotNull() .WithError(Errors.Metadata.MetadataCannotBeNull) @@ -70,9 +70,13 @@ public class UpdateAlbumCommandValidator : AbstractValidator .When(m => m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); - metadata.RuleFor(m => m!.ReleaseType) + metadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleForEach(m => m!.ReleaseTypes) .IsInEnum() - .When(m => m!.ReleaseType is not null) .WithError(Errors.Music.UnknownMusicReleaseType); metadata.RuleFor(m => m!.ReleaseStatus) @@ -206,15 +210,20 @@ public class UpdateAlbumCommandValidator : AbstractValidator .When(m => m!.OriginalLanguage is not null); }); - // Validates the physical characteristics of the album: format and catalog number. + // Validates the physical characteristics of the album: format, packaging, catalog number and barcode. RuleFor(command => command.MediaFormat) .IsInEnum() .When(command => command.MediaFormat is not null) .WithError(Errors.Music.UnknownMusicMediaFormat); - RuleFor(command => command.CatalogNumber) + RuleFor(command => command.Packaging) + .IsInEnum() + .When(command => command.Packaging is not null) + .WithError(Errors.Music.UnknownMusicReleasePackaging); + + RuleForEach(command => command.CatalogNumbers) .MaximumLength(50) - .When(command => command.CatalogNumber is not null) + .When(command => command.CatalogNumbers is not null) .WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); RuleFor(command => command.Barcode) diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommand.cs index 7fb265bd..f592e656 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommand.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -13,17 +15,23 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists /// Command for adding an artist, together with the albums of the artist and the tracks of those albums. /// /// The unique identifier of the media library this artist belongs to, taken from the route. -/// The name of the artist. +/// The metadata of the artist. /// The website of the artist, if applicable. /// The MusicBrainz identifier of the artist, if applicable. +/// The list of IPI codes of the artist. +/// The list of ISNI codes of the artist. /// The list of media contributors that make up the artist. +/// The list of ratings for the artist. /// The list of albums of the artist, each with its own list of tracks. -[DebuggerDisplay("Name: {Name}")] +[DebuggerDisplay("Name: {Metadata.Name}")] public record AddArtistCommand( string? LibraryId, - string? Name, + MusicArtistMetadataDto? Metadata, string? Website, Guid? MusicBrainzArtistId, + List? Ipis, + List? Isnis, List? Contributors, + List? Ratings, List? Albums ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidator.cs index 4337ed35..41d69942 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidator.cs @@ -28,13 +28,115 @@ public class AddArtistCommandValidator : AbstractValidator .WithError(Errors.Library.LibraryIdCannotBeEmpty); // Validates the identifying details of the artist. - RuleFor(command => command.Name) + RuleFor(command => command.Metadata) .NotNull() - .NotEmpty() - .WithError(Errors.Music.ArtistNameCannotBeEmpty) - .MaximumLength(255) - .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(metadata => + { + metadata.RuleFor(m => m!.Name) + .NotNull() + .NotEmpty() + .WithError(Errors.Music.ArtistNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + metadata.RuleFor(m => m!.SortName) + .MaximumLength(255) + .When(m => m!.SortName is not null) + .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Type) + .IsInEnum() + .When(m => m!.Type is not null) + .WithError(Errors.Music.UnknownMusicArtistType); + + metadata.RuleFor(m => m!.Gender) + .IsInEnum() + .When(m => m!.Gender is not null) + .WithError(Errors.Music.UnknownMusicArtistGender); + + metadata.RuleFor(m => m!.Country) + .Length(2) + .When(m => m!.Country is not null) + .WithError(Errors.Music.CountryMustBeMaximum2CharactersLong); + + metadata.RuleFor(m => m!.Area!.Name) + .NotEmpty() + .WithError(Errors.Music.AreaNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AreaNameMustBeMaximum255CharactersLong) + .When(m => m!.Area is not null); + + metadata.RuleFor(m => m!.BeginArea!.Name) + .NotEmpty() + .WithError(Errors.Music.AreaNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AreaNameMustBeMaximum255CharactersLong) + .When(m => m!.BeginArea is not null); + + metadata.RuleFor(m => m!.EndArea!.Name) + .NotEmpty() + .WithError(Errors.Music.AreaNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AreaNameMustBeMaximum255CharactersLong) + .When(m => m!.EndArea is not null); + + metadata.RuleForEach(m => m!.Aliases) + .ChildRules(alias => + { + alias.RuleFor(a => a.Name) + .NotEmpty() + .WithError(Errors.Music.ArtistAliasNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.ArtistAliasNameMustBeMaximum255CharactersLong); + + alias.RuleFor(a => a.SortName) + .MaximumLength(255) + .When(a => a.SortName is not null) + .WithError(Errors.Music.ArtistAliasNameMustBeMaximum255CharactersLong); + + alias.RuleFor(a => a.Type) + .MaximumLength(50) + .When(a => a.Type is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + + alias.RuleFor(a => a.Locale) + .MaximumLength(20) + .When(a => a.Locale is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + }); + + metadata.RuleFor(m => m!.Genres) + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + + metadata.RuleForEach(m => m!.Genres) + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + + metadata.RuleFor(m => m!.Tags) + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + metadata.RuleForEach(m => m!.Tags) + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + }); + + // Validates the website and the MusicBrainz identifiers of the artist. RuleFor(command => command.Website) .MaximumLength(2048) .When(command => command.Website is not null) @@ -45,6 +147,18 @@ public class AddArtistCommandValidator : AbstractValidator .When(command => command.MusicBrainzArtistId.HasValue) .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + RuleForEach(command => command.Ipis) + .NotEmpty() + .WithError(Errors.Music.IpiValueCannotBeEmpty) + .MaximumLength(20) + .WithError(Errors.Music.IpiValueMustBeMaximum20CharactersLong); + + RuleForEach(command => command.Isnis) + .NotEmpty() + .WithError(Errors.Music.IsniValueCannotBeEmpty) + .MaximumLength(20) + .WithError(Errors.Music.IsniValueMustBeMaximum20CharactersLong); + // Validates the media contributors that make up the artist. RuleFor(command => command.Contributors) .NotNull() @@ -64,6 +178,30 @@ public class AddArtistCommandValidator : AbstractValidator .WithError(Errors.MediaContributor.UnknownMediaContributorRole); }); + // Validates the ratings of the artist. + RuleFor(command => command.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + RuleForEach(command => command.Ratings) + .ChildRules(rating => + { + rating.RuleFor(r => r.Value) + .GreaterThan(0) + .WithError(Errors.Metadata.RatingValueMustBePositive) + .Must((ratingInstance, value) => value <= ratingInstance.MaxValue) + .WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + + rating.RuleFor(r => r.MaxValue) + .GreaterThan(0) + .WithError(Errors.Metadata.RatingMaxValueMustBePositive); + + rating.RuleFor(r => r.VoteCount) + .GreaterThanOrEqualTo(0) + .When(r => r.VoteCount.HasValue) + .WithError(Errors.Metadata.RatingVoteCountMustBePositive); + }); + // Validates each album created together with the artist, when the request carries albums. RuleFor(command => command.Albums) .NotNull() @@ -72,7 +210,7 @@ public class AddArtistCommandValidator : AbstractValidator RuleForEach(command => command.Albums) .ChildRules(album => { - // Validates the metadata of the album: title, lengths, release type and status, and disc and track counts. + // Validates the metadata of the album: title, lengths, release types and status, and disc and track counts. album.RuleFor(a => a!.Metadata) .NotNull() .WithError(Errors.Metadata.MetadataCannotBeNull) @@ -95,9 +233,13 @@ public class AddArtistCommandValidator : AbstractValidator .When(m => m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); - metadata.RuleFor(m => m!.ReleaseType) + metadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleForEach(m => m!.ReleaseTypes) .IsInEnum() - .When(m => m!.ReleaseType is not null) .WithError(Errors.Music.UnknownMusicReleaseType); metadata.RuleFor(m => m!.ReleaseStatus) @@ -231,15 +373,20 @@ public class AddArtistCommandValidator : AbstractValidator .When(m => m!.OriginalLanguage is not null); }); - // Validates the physical characteristics of the album: format and catalog number. + // Validates the physical characteristics of the album: format, packaging, catalog number and barcode. album.RuleFor(a => a!.MediaFormat) .IsInEnum() .When(a => a!.MediaFormat is not null) .WithError(Errors.Music.UnknownMusicMediaFormat); - album.RuleFor(a => a!.CatalogNumber) + album.RuleFor(a => a!.Packaging) + .IsInEnum() + .When(a => a!.Packaging is not null) + .WithError(Errors.Music.UnknownMusicReleasePackaging); + + album.RuleForEach(a => a!.CatalogNumbers) .MaximumLength(50) - .When(a => a!.CatalogNumber is not null) + .When(a => a!.CatalogNumbers is not null) .WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); album.RuleFor(a => a!.Barcode) @@ -349,6 +496,11 @@ public class AddArtistCommandValidator : AbstractValidator .When(m => m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.ReleaseInfo) .NotNull() .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) @@ -476,11 +628,6 @@ public class AddArtistCommandValidator : AbstractValidator .When(t => t!.MusicBrainzTrackId.HasValue) .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - track.RuleFor(t => t!.MusicBrainzWorkId) - .Must(musicBrainzWorkId => musicBrainzWorkId != Guid.Empty) - .When(t => t!.MusicBrainzWorkId.HasValue) - .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - // Validates the ordering and performance characteristics of the track. track.RuleFor(t => t!.TrackNumber) .NotNull() @@ -511,11 +658,17 @@ public class AddArtistCommandValidator : AbstractValidator .When(t => t!.Bpm.HasValue) .WithError(Errors.Music.BpmMustBeGreaterThanZero); - track.RuleFor(t => t!.Work) + // Validates the work the track is a recording of. + track.RuleFor(t => t!.Work!.Title) .MaximumLength(255) - .When(t => t!.Work is not null) + .When(t => t!.Work is not null && t.Work.Title is not null) .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + track.RuleFor(t => t!.Work!.MusicBrainzWorkId) + .Must(musicBrainzWorkId => musicBrainzWorkId is null || musicBrainzWorkId != Guid.Empty) + .When(t => t!.Work is not null) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + // Validates the moods and the ISRC codes of the track. track.RuleForEach(t => t!.Moods) .ChildRules(mood => diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommand.cs index 12343cfb..10181464 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommand.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -14,18 +16,24 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists /// /// The unique identifier of the media library this artist belongs to, taken from the route. /// The unique identifier of the artist, taken from the route. -/// The name of the artist. +/// The metadata of the artist. /// The website of the artist, if applicable. /// The MusicBrainz identifier of the artist, if applicable. +/// The list of IPI codes of the artist. +/// The list of ISNI codes of the artist. /// The list of media contributors that make up the artist. +/// The list of ratings for the artist. /// The list of albums of the artist, each with its own list of tracks. -[DebuggerDisplay("Name: {Name}")] +[DebuggerDisplay("Name: {Metadata.Name}")] public record UpdateArtistCommand( string? LibraryId, string? ArtistId, - string? Name, + MusicArtistMetadataDto? Metadata, string? Website, Guid? MusicBrainzArtistId, + List? Ipis, + List? Isnis, List? Contributors, + List? Ratings, List? Albums ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidator.cs index 91c44dd3..6c1d80de 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidator.cs @@ -17,7 +17,7 @@ public class UpdateArtistCommandValidator : AbstractValidator public UpdateArtistCommandValidator() { - // Validates the identifier of the media library that owns the artist, taken from the route. + // Validates the identifier of the media library that will own the artist, taken from the route. RuleFor(command => command.LibraryId) .NotEmpty() .WithError(Errors.Library.LibraryIdCannotBeEmpty); @@ -38,13 +38,115 @@ public class UpdateArtistCommandValidator : AbstractValidator command.Name) + RuleFor(command => command.Metadata) .NotNull() - .NotEmpty() - .WithError(Errors.Music.ArtistNameCannotBeEmpty) - .MaximumLength(255) - .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(metadata => + { + metadata.RuleFor(m => m!.Name) + .NotNull() + .NotEmpty() + .WithError(Errors.Music.ArtistNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + metadata.RuleFor(m => m!.SortName) + .MaximumLength(255) + .When(m => m!.SortName is not null) + .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Type) + .IsInEnum() + .When(m => m!.Type is not null) + .WithError(Errors.Music.UnknownMusicArtistType); + + metadata.RuleFor(m => m!.Gender) + .IsInEnum() + .When(m => m!.Gender is not null) + .WithError(Errors.Music.UnknownMusicArtistGender); + + metadata.RuleFor(m => m!.Country) + .Length(2) + .When(m => m!.Country is not null) + .WithError(Errors.Music.CountryMustBeMaximum2CharactersLong); + + metadata.RuleFor(m => m!.Area!.Name) + .NotEmpty() + .WithError(Errors.Music.AreaNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AreaNameMustBeMaximum255CharactersLong) + .When(m => m!.Area is not null); + + metadata.RuleFor(m => m!.BeginArea!.Name) + .NotEmpty() + .WithError(Errors.Music.AreaNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AreaNameMustBeMaximum255CharactersLong) + .When(m => m!.BeginArea is not null); + + metadata.RuleFor(m => m!.EndArea!.Name) + .NotEmpty() + .WithError(Errors.Music.AreaNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AreaNameMustBeMaximum255CharactersLong) + .When(m => m!.EndArea is not null); + + metadata.RuleForEach(m => m!.Aliases) + .ChildRules(alias => + { + alias.RuleFor(a => a.Name) + .NotEmpty() + .WithError(Errors.Music.ArtistAliasNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.ArtistAliasNameMustBeMaximum255CharactersLong); + + alias.RuleFor(a => a.SortName) + .MaximumLength(255) + .When(a => a.SortName is not null) + .WithError(Errors.Music.ArtistAliasNameMustBeMaximum255CharactersLong); + + alias.RuleFor(a => a.Type) + .MaximumLength(50) + .When(a => a.Type is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + + alias.RuleFor(a => a.Locale) + .MaximumLength(20) + .When(a => a.Locale is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + }); + + metadata.RuleFor(m => m!.Genres) + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + + metadata.RuleForEach(m => m!.Genres) + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + + metadata.RuleFor(m => m!.Tags) + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + metadata.RuleForEach(m => m!.Tags) + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + }); + + // Validates the website and the MusicBrainz identifiers of the artist. RuleFor(command => command.Website) .MaximumLength(2048) .When(command => command.Website is not null) @@ -55,6 +157,18 @@ public class UpdateArtistCommandValidator : AbstractValidator command.MusicBrainzArtistId.HasValue) .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + RuleForEach(command => command.Ipis) + .NotEmpty() + .WithError(Errors.Music.IpiValueCannotBeEmpty) + .MaximumLength(20) + .WithError(Errors.Music.IpiValueMustBeMaximum20CharactersLong); + + RuleForEach(command => command.Isnis) + .NotEmpty() + .WithError(Errors.Music.IsniValueCannotBeEmpty) + .MaximumLength(20) + .WithError(Errors.Music.IsniValueMustBeMaximum20CharactersLong); + // Validates the media contributors that make up the artist. RuleFor(command => command.Contributors) .NotNull() @@ -74,7 +188,31 @@ public class UpdateArtistCommandValidator : AbstractValidator command.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + RuleForEach(command => command.Ratings) + .ChildRules(rating => + { + rating.RuleFor(r => r.Value) + .GreaterThan(0) + .WithError(Errors.Metadata.RatingValueMustBePositive) + .Must((ratingInstance, value) => value <= ratingInstance.MaxValue) + .WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + + rating.RuleFor(r => r.MaxValue) + .GreaterThan(0) + .WithError(Errors.Metadata.RatingMaxValueMustBePositive); + + rating.RuleFor(r => r.VoteCount) + .GreaterThanOrEqualTo(0) + .When(r => r.VoteCount.HasValue) + .WithError(Errors.Metadata.RatingVoteCountMustBePositive); + }); + + // Validates each album created together with the artist, when the request carries albums. RuleFor(command => command.Albums) .NotNull() .WithError(Errors.Music.AlbumsListCannotBeNull); @@ -88,7 +226,7 @@ public class UpdateArtistCommandValidator : AbstractValidator a!.AlbumId.HasValue) .WithError(Errors.Music.AlbumIdCannotBeEmpty); - // Validates the metadata of the album: title, lengths, release type and status, and disc and track counts. + // Validates the metadata of the album: title, lengths, release types and status, and disc and track counts. album.RuleFor(a => a!.Metadata) .NotNull() .WithError(Errors.Metadata.MetadataCannotBeNull) @@ -111,9 +249,13 @@ public class UpdateArtistCommandValidator : AbstractValidator m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); - metadata.RuleFor(m => m!.ReleaseType) + metadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleForEach(m => m!.ReleaseTypes) .IsInEnum() - .When(m => m!.ReleaseType is not null) .WithError(Errors.Music.UnknownMusicReleaseType); metadata.RuleFor(m => m!.ReleaseStatus) @@ -247,15 +389,20 @@ public class UpdateArtistCommandValidator : AbstractValidator m!.OriginalLanguage is not null); }); - // Validates the physical characteristics of the album: format and catalog number. + // Validates the physical characteristics of the album: format, packaging, catalog number and barcode. album.RuleFor(a => a!.MediaFormat) .IsInEnum() .When(a => a!.MediaFormat is not null) .WithError(Errors.Music.UnknownMusicMediaFormat); - album.RuleFor(a => a!.CatalogNumber) + album.RuleFor(a => a!.Packaging) + .IsInEnum() + .When(a => a!.Packaging is not null) + .WithError(Errors.Music.UnknownMusicReleasePackaging); + + album.RuleForEach(a => a!.CatalogNumbers) .MaximumLength(50) - .When(a => a!.CatalogNumber is not null) + .When(a => a!.CatalogNumbers is not null) .WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); album.RuleFor(a => a!.Barcode) @@ -371,6 +518,11 @@ public class UpdateArtistCommandValidator : AbstractValidator m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.ReleaseInfo) .NotNull() .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) @@ -498,11 +650,6 @@ public class UpdateArtistCommandValidator : AbstractValidator t!.MusicBrainzTrackId.HasValue) .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - track.RuleFor(t => t!.MusicBrainzWorkId) - .Must(musicBrainzWorkId => musicBrainzWorkId != Guid.Empty) - .When(t => t!.MusicBrainzWorkId.HasValue) - .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - // Validates the ordering and performance characteristics of the track. track.RuleFor(t => t!.TrackNumber) .NotNull() @@ -533,11 +680,17 @@ public class UpdateArtistCommandValidator : AbstractValidator t!.Bpm.HasValue) .WithError(Errors.Music.BpmMustBeGreaterThanZero); - track.RuleFor(t => t!.Work) + // Validates the work the track is a recording of. + track.RuleFor(t => t!.Work!.Title) .MaximumLength(255) - .When(t => t!.Work is not null) + .When(t => t!.Work is not null && t.Work.Title is not null) .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + track.RuleFor(t => t!.Work!.MusicBrainzWorkId) + .Must(musicBrainzWorkId => musicBrainzWorkId is null || musicBrainzWorkId != Guid.Empty) + .When(t => t!.Work is not null) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + // Validates the moods and the ISRC codes of the track. track.RuleForEach(t => t!.Moods) .ChildRules(mood => diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs new file mode 100644 index 00000000..1754343c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Interface for the service for storing the artwork of a music library item, an album or an artist, into the internal media directory and serving its relative path. +/// +public interface IMusicArtworkService +{ + /// + /// Stores the of the album into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null); + + /// + /// Deletes the stored artwork of the album from the internal media directory. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. + /// An representing either a successful operation, or an error. + Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null); + + /// + /// Stores the of the artist into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken); + + /// + /// Deletes the stored artwork of the artist from the internal media directory. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// An representing either a successful operation, or an error. + Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs index 942f87c4..515c0ae9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs @@ -25,30 +25,29 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks. /// The script used by the language of the track, if applicable. /// The musical key of the track, if applicable. /// The tempo of the track in beats per minute, if applicable. -/// The title of the work the track is a recording of, if applicable. +/// The work the track is a recording of, if applicable. /// The MusicBrainz identifier of the recording, if applicable. /// The MusicBrainz identifier of the track, if applicable. -/// The MusicBrainz identifier of the work, if applicable. /// The list of moods of the track. /// The list of ISRC of the track. /// The list of media contributors that performed on the track. /// The list of ratings for this track. +/// The Id of the track, when the track already exists. [DebuggerDisplay("Title: {Metadata.Title}")] public record AddTrackCommand( string? LibraryId, string? ArtistId, string? AlbumId, string? Path, - AudioMetadataDto? Metadata, + MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, string? Script, MusicKey? Key, int? Bpm, - string? Work, + MusicWorkDto? Work, Guid? MusicBrainzRecordingId, Guid? MusicBrainzTrackId, - Guid? MusicBrainzWorkId, List? Moods, List? Isrcs, List? Contributors, diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidator.cs index 265649e1..ed5abad7 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidator.cs @@ -76,6 +76,11 @@ public class AddTrackCommandValidator : AbstractValidator .When(m => m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.ReleaseInfo) .NotNull() .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) @@ -203,11 +208,6 @@ public class AddTrackCommandValidator : AbstractValidator .When(command => command.MusicBrainzTrackId.HasValue) .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - RuleFor(command => command.MusicBrainzWorkId) - .Must(musicBrainzWorkId => musicBrainzWorkId != Guid.Empty) - .When(command => command.MusicBrainzWorkId.HasValue) - .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - // Validates the ordering and performance characteristics of the track. RuleFor(command => command.TrackNumber) .NotNull() @@ -238,11 +238,17 @@ public class AddTrackCommandValidator : AbstractValidator .When(command => command.Bpm.HasValue) .WithError(Errors.Music.BpmMustBeGreaterThanZero); - RuleFor(command => command.Work) + // Validates the work the track is a recording of. + RuleFor(command => command.Work!.Title) .MaximumLength(255) - .When(command => command.Work is not null) + .When(command => command.Work is not null && command.Work.Title is not null) .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + RuleFor(command => command.Work!.MusicBrainzWorkId) + .Must(musicBrainzWorkId => musicBrainzWorkId is null || musicBrainzWorkId != Guid.Empty) + .When(command => command.Work is not null) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + // Validates the moods and the ISRC codes of the track. RuleForEach(command => command.Moods) .ChildRules(mood => diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs index 2f67a920..9f5c15f0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs @@ -26,10 +26,9 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks. /// The script used by the language of the track, if applicable. /// The musical key of the track, if applicable. /// The tempo of the track in beats per minute, if applicable. -/// The title of the work the track is a recording of, if applicable. +/// The work the track is a recording of, if applicable. /// The MusicBrainz identifier of the recording, if applicable. /// The MusicBrainz identifier of the track, if applicable. -/// The MusicBrainz identifier of the work, if applicable. /// The list of moods of the track. /// The list of ISRC of the track. /// The list of media contributors that performed on the track. @@ -41,16 +40,15 @@ public record UpdateTrackCommand( string? AlbumId, string? TrackId, string? Path, - AudioMetadataDto? Metadata, + MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, string? Script, MusicKey? Key, int? Bpm, - string? Work, + MusicWorkDto? Work, Guid? MusicBrainzRecordingId, Guid? MusicBrainzTrackId, - Guid? MusicBrainzWorkId, List? Moods, List? Isrcs, List? Contributors, diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs index 0ebf84e5..aee75a3e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs @@ -86,6 +86,11 @@ public class UpdateTrackCommandValidator : AbstractValidator .When(m => m!.Description is not null) .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.Disambiguation) + .MaximumLength(255) + .When(m => m!.Disambiguation is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + trackMetadata.RuleFor(m => m!.ReleaseInfo) .NotNull() .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) @@ -213,11 +218,6 @@ public class UpdateTrackCommandValidator : AbstractValidator .When(command => command.MusicBrainzTrackId.HasValue) .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - RuleFor(command => command.MusicBrainzWorkId) - .Must(musicBrainzWorkId => musicBrainzWorkId != Guid.Empty) - .When(command => command.MusicBrainzWorkId.HasValue) - .WithError(Errors.Music.MusicBrainzIdInvalidFormat); - // Validates the ordering and performance characteristics of the track. RuleFor(command => command.TrackNumber) .NotNull() @@ -248,11 +248,17 @@ public class UpdateTrackCommandValidator : AbstractValidator .When(command => command.Bpm.HasValue) .WithError(Errors.Music.BpmMustBeGreaterThanZero); - RuleFor(command => command.Work) + // Validates the work the track is a recording of. + RuleFor(command => command.Work!.Title) .MaximumLength(255) - .When(command => command.Work is not null) + .When(command => command.Work is not null && command.Work.Title is not null) .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + RuleFor(command => command.Work!.MusicBrainzWorkId) + .Must(musicBrainzWorkId => musicBrainzWorkId is null || musicBrainzWorkId != Guid.Empty) + .When(command => command.Work is not null) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + // Validates the moods and the ISRC codes of the track. RuleForEach(command => command.Moods) .ChildRules(mood => diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index 995a3ee6..e1ff00bf 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using System.Diagnostics; #endregion @@ -17,6 +18,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. +/// The ordered parts of the template describing the structure of the media library on disk. [DebuggerDisplay("Title: {Title}")] public record AddLibraryCommand( string? Title, @@ -27,5 +29,6 @@ public record AddLibraryCommand( bool IsLocked, bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, - bool ShouldSkipUnchangedDirectoriesDuringScan + bool ShouldSkipUnchangedDirectoriesDuringScan, + LibraryPathTemplatePartDto[]? PathTemplateParts ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 44e6272e..7372692d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -11,6 +11,8 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; @@ -39,6 +41,7 @@ public class AddLibraryCommandHandler : ICommandHandler _validator; /// @@ -49,6 +52,7 @@ public class AddLibraryCommandHandler : ICommandHandlerInjected service for the queue of domain events. /// Injected facade service for environment contextual services. /// Injected store of the provider configurations of the media libraries. + /// Injected service for validating and resolving the path templates of the media libraries. /// Injected unit of work for interacting with the data access layer repositories. /// Injected validator for application validation rules. public AddLibraryCommandHandler( @@ -57,6 +61,7 @@ public class AddLibraryCommandHandler : ICommandHandler validator) { @@ -66,6 +71,7 @@ public class AddLibraryCommandHandler : ICommandHandler(command.LibraryType!); + + // A library always carries a path template: the one provided by the user, or the ideal structure of the library type as its default. + Result> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts(); + if (pathTemplatePartsResult.IsFailure) + return pathTemplatePartsResult.Errors; + Result pathTemplateResult = _pathTemplateService.ResolveTemplate(libraryType, pathTemplatePartsResult.Value); + if (pathTemplateResult.IsFailure) + return pathTemplateResult.Errors; + // Create a domain library object. Result createLibraryResult = Library.Create( UserId.Create(userId), command.Title!, - Enum.Parse(command.LibraryType!), + libraryType, command.ContentLocations!, Optional.FromNullable(command.CoverImage), command.IsEnabled, @@ -120,6 +136,7 @@ public class AddLibraryCommandHandler : ICommandHandler ensureProviderConfigurationsResult = await _providerConfigurationStore.EnsureProviderConfigurationsAsync( - createLibraryResult.Value.Id.Value, Enum.Parse(command.LibraryType!), cancellationToken).ConfigureAwait(false); + createLibraryResult.Value.Id.Value, libraryType, cancellationToken).ConfigureAwait(false); if (ensureProviderConfigurationsResult.IsFailure) return ensureProviderConfigurationsResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs index b439d346..a1ad34cb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs @@ -41,5 +41,17 @@ public class AddLibraryCommandValidator : AbstractValidator .WithError(Errors.Library.TitleCannotBeEmpty) .MaximumLength(255) .WithError(Errors.Library.TitleMustBeMaximum255CharactersLong); + + RuleForEach(command => command.PathTemplateParts) + .ChildRules(part => + { + part.RuleFor(pathPart => pathPart.Kind) + .NotEmpty() + .WithError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType); + part.RuleFor(pathPart => pathPart.Representation) + .NotEmpty() + .When(pathPart => !string.Equals(pathPart.Kind, nameof(LibraryPathPartKind.Separator), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.Library.PathTemplateLiteralCannotBeEmpty); + }); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs index 63fd4be0..27965444 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using System; using System.Diagnostics; #endregion @@ -20,6 +21,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. +/// The ordered parts of the template describing the structure of the media library on disk. [DebuggerDisplay("Title: {Title}")] public record UpdateLibraryCommand( Guid Id, @@ -32,5 +34,6 @@ public record UpdateLibraryCommand( bool IsLocked, bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, - bool ShouldSkipUnchangedDirectoriesDuringScan + bool ShouldSkipUnchangedDirectoriesDuringScan, + LibraryPathTemplatePartDto[]? PathTemplateParts ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 42fe46cb..cc961c0b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -12,6 +12,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; @@ -43,6 +44,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler _validator; /// @@ -53,6 +55,7 @@ public class UpdateLibraryCommandHandler : ICommandHandlerInjected service for the queue of domain events. /// Injected facade service for environment contextual services. /// Injected store of the provider configurations of the media libraries. + /// Injected service for validating and resolving the path templates of the media libraries. /// Injected unit of work for interacting with the data access layer repositories. /// Injected validator for application validation rules. public UpdateLibraryCommandHandler( @@ -61,6 +64,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler validator) { @@ -70,6 +74,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler(command.LibraryType!); + + // A library always carries a path template: the one provided by the user, or the ideal structure of the library type as its default. + Result> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts(); + if (pathTemplatePartsResult.IsFailure) + return pathTemplatePartsResult.Errors; + Result pathTemplateResult = _pathTemplateService.ResolveTemplate(newLibraryType, pathTemplatePartsResult.Value); + if (pathTemplateResult.IsFailure) + return pathTemplateResult.Errors; + Result createLibraryResult = Library.Create( LibraryId.Create(command.Id), UserId.Create(command.OwnerId), @@ -136,6 +150,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler ScanId.Create(libraryScan.Id))] ); if (createLibraryResult.IsFailure) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs index 53ed0211..febdd879 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs @@ -53,5 +53,17 @@ public class UpdateLibraryCommandValidator : AbstractValidator command.PathTemplateParts) + .ChildRules(part => + { + part.RuleFor(pathPart => pathPart.Kind) + .NotEmpty() + .WithError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType); + part.RuleFor(pathPart => pathPart.Representation) + .NotEmpty() + .When(pathPart => !string.Equals(pathPart.Kind, nameof(LibraryPathPartKind.Separator), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.Library.PathTemplateLiteralCannotBeEmpty); + }); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs new file mode 100644 index 00000000..1bab3103 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Deletion; + +/// +/// Deletion strategy for the media library items of the books media library type. The book stored at the deleted path is removed, together with its stored artwork. +/// +internal sealed class BooksMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IBookArtworkService _bookArtworkService; + private readonly ILogger _logger; + + /// + /// The media library type that this deletion strategy supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for storing the artwork of the books. + /// Injected logger used to report the issues encountered while deleting the media library item. + public BooksMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger logger) + { + _unitOfWork = unitOfWork; + _bookArtworkService = bookArtworkService; + _logger = logger; + } + + /// + /// Deletes the book stored at the provided in the media library identified by , together with its stored artwork. + /// + /// The Id of the media library whose book is deleted. + /// The file system path of the book to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken) + { + // Load the book stored at the deleted path, which might have been already removed. + Result getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, path, cancellationToken).ConfigureAwait(false); + if (getBookResult.IsFailure) + return getBookResult.Errors; + BookEntity? book = getBookResult.Value; + if (book is null) + return Result.Success; + + // Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + return getLibraryResult.IsFailure ? getLibraryResult.Errors : Errors.Library.LibraryNotFound; + LibraryEntity library = getLibraryResult.Value; + + Result> getAuthorsResult = await _unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], cancellationToken).ConfigureAwait(false); + if (getAuthorsResult.IsFailure) + return getAuthorsResult.Errors; + string authorName = getAuthorsResult.Value.TryGetValue(book.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; + + Result deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title); + if (deleteArtworkResult.IsFailure) + _logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path); + + // Delete the book, whose stored artwork and participations are removed by the database cascade. + Result deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false); + if (deleteBookResult.IsFailure) + return deleteBookResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/IMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/IMediaLibraryItemDeletionStrategy.cs new file mode 100644 index 00000000..71aeda3a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/IMediaLibraryItemDeletionStrategy.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Deletion; + +/// +/// Interface defining the strategy used to delete a media library item that is no longer present in the media library scan snapshot, for a specific media library type. +/// +public interface IMediaLibraryItemDeletionStrategy +{ + /// + /// The media library type that this deletion strategy supports. + /// + LibraryType SupportedLibraryType { get; } + + /// + /// Deletes the media library item stored at the provided in the media library identified by . + /// + /// The Id of the media library whose item is deleted. + /// The file system path of the media library item to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs new file mode 100644 index 00000000..7acb3af4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs @@ -0,0 +1,121 @@ +#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 Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Deletion; + +/// +/// Deletion strategy for the media library items of the music media library type. The track stored at the deleted path is removed, together with its stored artwork, +/// and the album and the artist that are left with no children after the removal are removed as well. +/// +internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// The media library type that this deletion strategy supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Music; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public MusicMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Deletes the track stored at the provided in the media library identified by , together with its stored artwork, + /// and the album and the artist that are left with no children after the removal. + /// + /// The Id of the media library whose track is deleted. + /// The file system path of the track to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken) + { + // Load the track stored at the deleted path, which might have been already removed. + Result getTrackResult = await _unitOfWork.TrackRepository.GetByPathAsync(libraryId, path, cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + TrackEntity? track = getTrackResult.Value; + if (track is null) + return Result.Success; + + Guid trackId = track.Id; + Guid albumId = track.AlbumId; + + // Delete the stored artwork of the track, which has no cascade relationship because the artwork table is shared by all the music library item types. + Result deleteTrackArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken).ConfigureAwait(false); + if (deleteTrackArtworkResult.IsFailure) + return deleteTrackArtworkResult.Errors; + + Result deleteTrackResult = await _unitOfWork.TrackRepository.DeleteByIdAsync(trackId, cancellationToken).ConfigureAwait(false); + if (deleteTrackResult.IsFailure) + return deleteTrackResult.Errors; + + // Load the album the deleted track belonged to, to determine whether it is left with no children. + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + AlbumEntity? album = getAlbumResult.Value; + if (album is null) + return await SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Guid artistId = album.ArtistId; + + Result> getRemainingTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false); + if (getRemainingTracksResult.IsFailure) + return getRemainingTracksResult.Errors; + // The deleted track is still tracked by the change tracker until the changes are saved, so it is excluded explicitly. + if (getRemainingTracksResult.Value.All(remainingTrack => remainingTrack.Id == trackId)) + { + Result deleteAlbumArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false); + if (deleteAlbumArtworkResult.IsFailure) + return deleteAlbumArtworkResult.Errors; + + Result deleteAlbumResult = await _unitOfWork.AlbumRepository.DeleteByIdAsync(albumId, cancellationToken).ConfigureAwait(false); + if (deleteAlbumResult.IsFailure) + return deleteAlbumResult.Errors; + + Result> getRemainingAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false); + if (getRemainingAlbumsResult.IsFailure) + return getRemainingAlbumsResult.Errors; + // The deleted album is still tracked by the change tracker until the changes are saved, so it is excluded explicitly. + if (getRemainingAlbumsResult.Value.All(remainingAlbum => remainingAlbum.Id == albumId)) + { + Result deleteArtistArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false); + if (deleteArtistArtworkResult.IsFailure) + return deleteArtistArtworkResult.Errors; + + Result deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false); + if (deleteArtistResult.IsFailure) + return deleteArtistResult.Errors; + } + } + + return await SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Persists the changes made to the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> SaveChangesAsync(CancellationToken cancellationToken) + { + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return saveChangesResult.IsFailure ? saveChangesResult.Errors : Result.Success; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs index 7c68e86b..8d63a811 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs @@ -1,15 +1,17 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Application.Core.MediaLibrary.Management.Deletion; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,24 +20,24 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// /// Handler for the domain event raised when a media library item is no longer present in the media library scan snapshot. -/// The book stored at the deleted path is removed, together with its stored artwork. +/// The media library item stored at the deleted path is removed by the deletion strategy of the media library type it belongs to. /// public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler { private readonly IUnitOfWork _unitOfWork; - private readonly IBookArtworkService _bookArtworkService; + private readonly IEnumerable _mediaLibraryItemDeletionStrategies; private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for storing the artwork of the books. + /// Injected deletion strategies, one for each supported media library type. /// Injected logger used to report the issues encountered while deleting the media library item. - public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger logger) + public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IEnumerable mediaLibraryItemDeletionStrategies, ILogger logger) { _unitOfWork = unitOfWork; - _bookArtworkService = bookArtworkService; + _mediaLibraryItemDeletionStrategies = mediaLibraryItemDeletionStrategies; _logger = logger; } @@ -48,36 +50,23 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false); - if (getBookResult.IsFailure) - throw new EventualConsistencyException(getBookResult.FirstError, getBookResult.Errors); - BookEntity? book = getBookResult.Value; - if (book is null) - return; - - // Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed. + // Load the media library, whose type determines the deletion strategy to use. Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + if (getLibraryResult.IsFailure) throw new EventualConsistencyException(getLibraryResult.FirstError, getLibraryResult.Errors); - LibraryEntity library = getLibraryResult.Value; + if (getLibraryResult.Value is null) + throw new EventualConsistencyException(Errors.Library.LibraryNotFound); + LibraryType libraryType = getLibraryResult.Value.LibraryType; - Result> getAuthorsResult = await _unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], cancellationToken).ConfigureAwait(false); - if (getAuthorsResult.IsFailure) - throw new EventualConsistencyException(getAuthorsResult.FirstError, getAuthorsResult.Errors); - string authorName = getAuthorsResult.Value.TryGetValue(book.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; + IMediaLibraryItemDeletionStrategy? deletionStrategy = _mediaLibraryItemDeletionStrategies.FirstOrDefault(strategy => strategy.SupportedLibraryType == libraryType); + if (deletionStrategy is null) + { + _logger.LogWarning("No deletion strategy exists for media library type '{LibraryType}', the item at path '{ItemPath}' was not deleted.", libraryType, domainEvent.Path); + return; + } - Result deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title); - if (deleteArtworkResult.IsFailure) - _logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path); - - // Delete the book, whose stored artwork and participations are removed by the database cascade. - Result deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false); - if (deleteBookResult.IsFailure) - throw new EventualConsistencyException(deleteBookResult.FirstError, deleteBookResult.Errors); - - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); + Result deleteItemResult = await deletionStrategy.DeleteItemAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false); + if (deleteItemResult.IsFailure) + throw new EventualConsistencyException(deleteItemResult.FirstError, deleteItemResult.Errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQuery.cs new file mode 100644 index 00000000..acf7fb9f --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; + +/// +/// Query for getting the path parts available for a media library type. +/// +/// The media library type whose available path parts are retrieved. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryPathTemplatePartsQuery( + string? LibraryType +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs new file mode 100644 index 00000000..ac64fcec --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; + +/// +/// Handler for the query to get the path template catalog available for a media library type. +/// +public class GetLibraryPathTemplatePartsQueryHandler : IQueryHandler> +{ + private readonly IReadOnlyList _catalogs; + + /// + /// Initializes a new instance of the class. + /// + /// Injected path part catalogs of the supported media library types. + public GetLibraryPathTemplatePartsQueryHandler(IEnumerable catalogs) + { + _catalogs = [.. catalogs]; + } + + /// + /// Handles the query to get the path template catalog available for a media library type. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the path template catalog, or an error message. + /// + public Task> HandleAsync(GetLibraryPathTemplatePartsQuery query, CancellationToken cancellationToken) + { + // the library type travels as a string taken from the route, and is matched against the enum the same way the create and update + // library commands do, so that a malformed type is reported as an unknown library type instead of silently returning an empty catalog. + if (!Enum.TryParse(query.LibraryType, ignoreCase: true, out LibraryType libraryType)) + return Task.FromResult>(DomainErrors.Library.UnknownLibraryType); + + // only the catalog registered for the requested library type applies, so the parts and the default structure offered to the user are + // type aware (music libraries get artist and release parts, book libraries get author and title parts, and so on). + ILibraryPathPartCatalog? catalog = _catalogs.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); + if (catalog is null) + // a library type without a catalog has no structure to describe, so an empty catalog is returned, which the client uses to hide the editor. + return Task.FromResult(Result.Success(new LibraryPathTemplateCatalogResponse([], []))); + + // the selectable parts describe what the user can drop into the template, together with the value type and the default on-disk representation of each part. + List parts = + [ + .. catalog.GetPartDefinitions().Select(definition => new LibraryPathPartDefinitionResponse( + definition.Kind.ToString(), + definition.ValueType.ToString(), + definition.DefaultRepresentation, + definition.IsOptionalByDefault)) + ]; + // the default template parts describe the ideal structure the application expects, pre-filled in the editor so the user only edits what deviates. + List defaultTemplateParts = + [ + .. catalog.GetDefaultTemplate().Parts.Select(part => new LibraryPathTemplatePartResponse(part.Kind.ToString(), part.Representation, part.IsOptional)) + ]; + return Task.FromResult(Result.Success(new LibraryPathTemplateCatalogResponse(parts, defaultTemplateParts))); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs index 44a547f4..7dbaa12e 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs @@ -12,6 +12,7 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. +/// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. public record UpdateUserSettingsCommand( @@ -20,6 +21,7 @@ public record UpdateUserSettingsCommand( bool ShouldIgnoreThePrefixForAlphaPicker, bool IsThemeCachingEnabled, bool ShouldAggregateMetadataWhenMissing, + bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, bool ShouldPreserveBookStyles ) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs index af92e828..73317f73 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -74,6 +74,7 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler /// Data transfer object for the artwork of a media item, provided by an artwork provider. /// +/// The type of the artwork, like the cover or the back of the media item. +/// The ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered. /// The local file system path of the artwork, when the artwork is a local file. /// The remote URL of the artwork, when the artwork is fetched over the web. -[DebuggerDisplay("LocalPath: {LocalPath}, RemoteUrl: {RemoteUrl}")] +/// Whether a local artwork is a temporary file produced by the provider, which is deleted after the artwork is stored. +[DebuggerDisplay("Type: {Type}, Ordinal: {Ordinal}, LocalPath: {LocalPath}, RemoteUrl: {RemoteUrl}")] public sealed record ArtworkDto( + ArtworkType Type, + int Ordinal, string? LocalPath, - string? RemoteUrl + string? RemoteUrl, + bool IsTemporary = false ); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDto.cs index 3510ef65..7c77da46 100644 --- a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDto.cs +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDto.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Collections.Generic; @@ -9,32 +11,60 @@ using System.Diagnostics; namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; /// -/// Data transfer object for the metadata of an album. +/// Data transfer object for the metadata of an album, returned by a metadata provider. /// /// The title of the album. Required. /// The original title of the album, if different from the current title. Optional. /// A brief description or summary of the album. Optional. +/// The disambiguation comment of the album, used to distinguish albums with the same title. Optional. /// The release information, including release date and other relevant details. Required. /// The language of the album. Optional. /// The original language of the album, if it has been translated. Optional. /// The list of tags that further describe or categorize the album. Required. /// The list of genres associated with the album. Required. -/// The type of the release. Optional. +/// The script used by the language of the release of the album. Optional. +/// The set of types of the release. Optional. /// The status of the release. Optional. +/// The physical or digital medium of the album. Optional. +/// The outermost physical packaging of the album. Optional. /// The number of discs of the release. Optional. /// The number of tracks of the release. Required. +/// The barcode of the album. Optional. +/// The catalog numbers of the album. Optional. +/// The name of the label that issued the album. Optional. +/// The ASIN (Amazon Standard Identification Number) of the album. Optional. +/// The MusicBrainz identifier of the release. Optional. +/// The MusicBrainz identifier of the release group. Optional. +/// The MusicBrainz identifier of the release artist. Optional. +/// The list of media contributors that performed on the album, each with the role they played. Required. +/// The list of ratings for the album. Required. +/// The title of the specific release (edition) the album files match, if different from the release group title. Optional. [DebuggerDisplay("Title: {Title}")] -public record AlbumMetadataDto( +public sealed record AlbumMetadataDto( string? Title, string? OriginalTitle, string? Description, + string? Disambiguation, ReleaseInfoDto? ReleaseInfo, LanguageInfoDto? Language, LanguageInfoDto? OriginalLanguage, List? Tags, List? Genres, - MusicReleaseType? ReleaseType, + string? Script, + List? ReleaseTypes, MusicReleaseStatus? ReleaseStatus, + MusicMediaFormat? MediaFormat, + MusicReleasePackaging? Packaging, int? TotalDiscs, - int? TotalTracks -); + int? TotalTracks, + string? Barcode, + List? CatalogNumbers, + string? Label, + string? ASIN, + Guid? MusicBrainzReleaseId, + Guid? MusicBrainzReleaseGroupId, + Guid? MusicBrainzReleaseArtistId, + List? Contributors, + List? Ratings, + string? ReleaseTitle = null +) : MetadataDto; diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataLookupDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataLookupDto.cs new file mode 100644 index 00000000..d226c02c --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataLookupDto.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for an album metadata lookup. +/// +/// The Id of the media library the album belongs to. +/// The file system path of a track of the album. +/// The MusicBrainz identifier of the release group of the album, if applicable. +/// The MusicBrainz identifier of the release of the album, if applicable. +/// The title of the album, if applicable. +/// The name of the artist of the album, if applicable. +/// The year the album was released, if applicable. +/// The number of tracks the local album has, if applicable. It is used to select a release whose tracklist matches the local files. +[DebuggerDisplay("Title: {Title}")] +public sealed record AlbumMetadataLookupDto( + Guid LibraryId, + string Path, + Guid? MusicBrainzReleaseGroupId = null, + Guid? MusicBrainzReleaseId = null, + string? Title = null, + string? ArtistName = null, + int? ReleaseYear = null, + int? TrackCount = null +) : MetadataLookupDto; diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataDto.cs new file mode 100644 index 00000000..cdd1b319 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataDto.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for the metadata of a music artist. +/// +/// The name of the artist. +/// The sort name of the artist, a variant of the name used when sorting artists, if applicable. +/// The disambiguation comment of the artist, used to distinguish artists with the same name, if applicable. +/// The type of the artist, if applicable. +/// The gender of the artist, applicable only to artists that are persons or characters, if applicable. +/// The ISO 3166-1 alpha-2 code of the country the artist is associated with, if applicable. +/// The area the artist is primarily identified with, if applicable. +/// The area the artist began in, if applicable. +/// The area the artist ended in, if applicable. +/// The date the artist started existing, if applicable. +/// The date the artist stopped existing, if applicable. +/// Whether the artist no longer exists. +/// The website of the artist, if applicable. +/// The MusicBrainz identifier of the artist, if applicable. +/// The list of IPI (Interested Party Information) codes of the artist. +/// The list of ISNI (International Standard Name Identifier) codes of the artist. +/// The list of alternative names of the artist. +/// The list of genres associated with the artist. +/// The list of tags that further describe or categorize the artist. +/// The list of ratings for the artist. +/// The list of media contributors that make up the artist, each with the role they played. +[DebuggerDisplay("Name: {Name}")] +public sealed record ArtistMetadataDto( + string? Name, + string? SortName, + string? Disambiguation, + MusicArtistType? Type, + MusicArtistGender? Gender, + string? Country, + MusicAreaDto? Area, + MusicAreaDto? BeginArea, + MusicAreaDto? EndArea, + DateOnly? LifeSpanBegin, + DateOnly? LifeSpanEnd, + bool IsEnded, + string? Website, + Guid? MusicBrainzArtistId, + List? Ipis, + List? Isnis, + List? Aliases, + List? Genres, + List? Tags, + List? Ratings, + List? Contributors +) : MetadataDto; diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataLookupDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataLookupDto.cs new file mode 100644 index 00000000..2c8321c6 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataLookupDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for a music artist metadata lookup. +/// +/// The Id of the media library the artist belongs to. +/// The file system path of a track of the artist. +/// The MusicBrainz identifier of the artist, if applicable. +/// The name of the artist, if applicable. +[DebuggerDisplay("Name: {Name}")] +public sealed record ArtistMetadataLookupDto( + Guid LibraryId, + string Path, + Guid? MusicBrainzArtistId = null, + string? Name = null +) : MetadataLookupDto; diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs index 5fa4deee..35114938 100644 --- a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs @@ -1,5 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -8,36 +11,60 @@ using System.Diagnostics; namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; /// -/// Data transfer object for the audio metadata of a track. +/// Data transfer object for the audio metadata of a track, returned by a metadata provider. /// /// The title of the track. Required. /// The original title of the track, if different from the current title. Optional. /// A brief description or summary of the track. Optional. +/// The disambiguation comment of the track, used to distinguish tracks with the same title. Optional. /// The release information, including release date and other relevant details. Required. /// The language of the track. Optional. /// The original language of the track, if it has been translated. Optional. /// The list of tags that further describe or categorize the track. Required. /// The list of genres associated with the track. Required. +/// The script used by the language of the track. Optional. +/// The musical key of the track. Optional. +/// The tempo of the track in beats per minute. Optional. +/// Whether the recording of the track is a video recording. +/// The work the track is a recording of, if applicable. Optional. +/// The list of ISRC (International Standard Recording Code) of the track. Optional. +/// The list of moods of the track. Optional. /// The duration of the audio of the track in seconds. Required. /// The sample rate of the audio of the track in Hz. Required. /// The number of audio channels of the track. Required. /// The bit depth of the audio of the track. Optional. /// The audio codec used by the track. Optional. /// The bitrate of the audio of the track in kbps. Optional. +/// The MusicBrainz identifier of the recording. Optional. +/// The MusicBrainz identifier of the track. Optional. +/// The list of media contributors that performed on the track, each with the role they played. Required. +/// The list of ratings for the track. Required. [DebuggerDisplay("Title: {Title}")] -public record AudioMetadataDto( +public sealed record AudioMetadataDto( string? Title, string? OriginalTitle, string? Description, + string? Disambiguation, ReleaseInfoDto? ReleaseInfo, LanguageInfoDto? Language, LanguageInfoDto? OriginalLanguage, List? Tags, List? Genres, + string? Script, + MusicKey? Key, + int? Bpm, + bool IsVideo, + MusicWorkDto? Work, + List? Isrcs, + List? Moods, int? DurationInSeconds, int? SampleRate, int? Channels, int? BitDepth, string? AudioCodec, - int? Bitrate -); + int? Bitrate, + Guid? MusicBrainzRecordingId, + Guid? MusicBrainzTrackId, + List? Contributors, + List? Ratings +) : MetadataDto; diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAlbumMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAlbumMetadataDto.cs new file mode 100644 index 00000000..40b9e138 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAlbumMetadataDto.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for the metadata of an album, as used by the API. +/// +/// +/// The identifiers, the contributors and the ratings of the album are kept alongside this object, as siblings, rather than inside it. +/// +/// The title of the album. Required. +/// The original title of the album, if different from the current title. Optional. +/// A brief description or summary of the album. Optional. +/// The disambiguation comment of the album, used to distinguish albums with the same title. Optional. +/// The release information, including release date and other relevant details. Required. +/// The language of the album. Optional. +/// The original language of the album, if it has been translated. Optional. +/// The list of tags that further describe or categorize the album. Required. +/// The list of genres associated with the album. Required. +/// The script used by the language of the release of the album. Optional. +/// The set of types of the release. Optional. +/// The status of the release. Optional. +/// The number of discs of the release. Optional. +/// The number of tracks of the release. Required. +/// The title of the specific release (edition) the album files match, if different from the release group title. Optional. +[DebuggerDisplay("Title: {Title}")] +public record MusicAlbumMetadataDto( + string? Title, + string? OriginalTitle, + string? Description, + string? Disambiguation, + ReleaseInfoDto? ReleaseInfo, + LanguageInfoDto? Language, + LanguageInfoDto? OriginalLanguage, + List? Tags, + List? Genres, + string? Script, + List? ReleaseTypes, + MusicReleaseStatus? ReleaseStatus, + int? TotalDiscs, + int? TotalTracks, + string? ReleaseTitle = null +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaDto.cs new file mode 100644 index 00000000..261ce850 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for a MusicBrainz area, the geographic area a music artist is associated with. +/// +/// The MusicBrainz identifier of the area. +/// The name of the area. +/// The sort name of the area, if applicable. +/// The disambiguation comment of the area, if applicable. +/// The MusicBrainz type of the area, if applicable. +/// The ISO 3166 code of the area, if applicable. +[DebuggerDisplay("Name: {Name}")] +public sealed record MusicAreaDto( + Guid? MusicBrainzAreaId, + string? Name, + string? SortName, + string? Disambiguation, + string? Type, + string? Iso3166Code +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistAliasDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistAliasDto.cs new file mode 100644 index 00000000..7777686d --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistAliasDto.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for an alternative name of a music artist. +/// +/// The name of the alias. +/// The sort name of the alias, if applicable. +/// The type of the alias, if applicable. +/// The locale the alias is used in, if applicable. +/// Whether this is the primary alias of the artist. +/// The date the alias began being used, if applicable. +/// The date the alias stopped being used, if applicable. +/// Whether the alias is no longer used. +[DebuggerDisplay("Name: {Name}")] +public sealed record MusicArtistAliasDto( + string? Name, + string? SortName, + string? Type, + string? Locale, + bool IsPrimary, + DateOnly? BeginDate, + DateOnly? EndDate, + bool IsEnded +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistMetadataDto.cs new file mode 100644 index 00000000..d271094c --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistMetadataDto.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for the metadata of a music artist, as used by the API. +/// +/// +/// The identifiers, the contributors and the ratings of the artist are kept alongside this object, as siblings, rather than inside it. +/// +/// The name of the artist. +/// The sort name of the artist, a variant of the name used when sorting artists, if applicable. +/// The disambiguation comment of the artist, used to distinguish artists with the same name, if applicable. +/// The type of the artist, if applicable. +/// The gender of the artist, applicable only to artists that are persons or characters, if applicable. +/// The ISO 3166-1 alpha-2 code of the country the artist is associated with, if applicable. +/// The area the artist is primarily identified with, if applicable. +/// The area the artist began in, if applicable. +/// The area the artist ended in, if applicable. +/// The date the artist started existing, if applicable. +/// The date the artist stopped existing, if applicable. +/// Whether the artist no longer exists. +/// The list of genres associated with the artist. +/// The list of tags that further describe or categorize the artist. +/// The list of alternative names of the artist. +[DebuggerDisplay("Name: {Name}")] +public record MusicArtistMetadataDto( + string? Name, + string? SortName, + string? Disambiguation, + MusicArtistType? Type, + MusicArtistGender? Gender, + string? Country, + MusicAreaDto? Area, + MusicAreaDto? BeginArea, + MusicAreaDto? EndArea, + DateOnly? LifeSpanBegin, + DateOnly? LifeSpanEnd, + bool IsEnded, + List? Genres, + List? Tags, + List? Aliases +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicTrackMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicTrackMetadataDto.cs new file mode 100644 index 00000000..cb088a29 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicTrackMetadataDto.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for the audio metadata of a track, as used by the API. +/// +/// +/// The identifiers, the contributors and the ratings of the track are kept alongside this object, as siblings, rather than inside it. +/// +/// The title of the track. Required. +/// The original title of the track, if different from the current title. Optional. +/// A brief description or summary of the track. Optional. +/// The disambiguation comment of the track, used to distinguish tracks with the same title. Optional. +/// The release information, including release date and other relevant details. Required. +/// The language of the track. Optional. +/// The original language of the track, if it has been translated. Optional. +/// The list of tags that further describe or categorize the track. Required. +/// The list of genres associated with the track. Required. +/// Whether the recording of the track is a video recording. +/// The duration of the audio of the track in seconds. Required. +/// The sample rate of the audio of the track in Hz. Required. +/// The number of audio channels of the track. Required. +/// The bit depth of the audio of the track. Optional. +/// The audio codec used by the track. Optional. +/// The bitrate of the audio of the track in kbps. Optional. +/// The AcoustID fingerprint identifier of the audio file of the track. Optional. +/// The ReplayGain track gain of the track in decibels. Optional. +/// The ReplayGain track peak of the track. Optional. +/// The ReplayGain album gain of the track in decibels. Optional. +/// The ReplayGain album peak of the track. Optional. +[DebuggerDisplay("Title: {Title}")] +public record MusicTrackMetadataDto( + string? Title, + string? OriginalTitle, + string? Description, + string? Disambiguation, + ReleaseInfoDto? ReleaseInfo, + LanguageInfoDto? Language, + LanguageInfoDto? OriginalLanguage, + List? Tags, + List? Genres, + bool IsVideo, + int? DurationInSeconds, + int? SampleRate, + int? Channels, + int? BitDepth, + string? AudioCodec, + int? Bitrate, + string? AcoustId = null, + decimal? ReplayGainTrackGain = null, + decimal? ReplayGainTrackPeak = null, + decimal? ReplayGainAlbumGain = null, + decimal? ReplayGainAlbumPeak = null +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicWorkDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicWorkDto.cs new file mode 100644 index 00000000..cf48182b --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicWorkDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for a MusicBrainz work, the musical composition a track is a recording of. +/// +/// +/// The contributors credited on the work are carried by the contributors of the metadata of the track. +/// +/// The MusicBrainz identifier of the work. +/// The title of the work. +/// The MusicBrainz type of the work, if applicable. +/// The list of languages of the work. +/// The list of ISWC (International Standard Musical Work Code) of the work. +[DebuggerDisplay("Title: {Title}")] +public sealed record MusicWorkDto( + Guid? MusicBrainzWorkId, + string? Title, + string? Type, + List? Languages, + List? Iswcs +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/TrackMetadataLookupDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/TrackMetadataLookupDto.cs new file mode 100644 index 00000000..f792fb6d --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/TrackMetadataLookupDto.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for a track metadata lookup. +/// +/// The Id of the media library the track belongs to. +/// The file system path of the track. +/// The MusicBrainz identifier of the recording of the track, if applicable. +/// The ISRC (International Standard Recording Code) of the track, if applicable. +/// The title of the track, if applicable. +/// The name of the artist of the track, if applicable. +/// The name of the release the track belongs to, if applicable. +/// The number of the track on its disc, if applicable. +/// The duration of the track in seconds, if applicable. +/// The MusicBrainz identifier of the release the track belongs to, if applicable. +/// The number of the disc the track belongs to, if applicable. +/// The MusicBrainz identifier of the work the track is a recording of, read from the tags, if applicable. It is used as a fallback when MusicBrainz does not link the recording to a work. +/// The title of the work the track is a recording of, read from the tags, if applicable. Its presence means the work of the tags is already complete, so the work is not resolved from MusicBrainz again. +[DebuggerDisplay("Title: {Title}")] +public sealed record TrackMetadataLookupDto( + Guid LibraryId, + string Path, + Guid? MusicBrainzRecordingId = null, + string? Isrc = null, + string? Title = null, + string? ArtistName = null, + string? ReleaseName = null, + int? TrackNumber = null, + int? DurationInSeconds = null, + Guid? MusicBrainzReleaseId = null, + int? DiscNumber = null, + Guid? MusicBrainzWorkId = null, + string? WorkTitle = null +) : MetadataLookupDto; diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequest.cs index e082c21a..cac68de1 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequest.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; @@ -17,8 +16,11 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Album /// /// The album metadata of the album. Required. /// The physical or digital medium of the album. Optional. +/// The outermost physical packaging of the album. Optional. /// The barcode of the album. Optional. -/// The catalog number of the album. Optional. +/// The catalog numbers of the album. Optional. +/// The name of the label that issued the album. Optional. +/// The ASIN (Amazon Standard Identification Number) of the album. Optional. /// The MusicBrainz identifier of the release. Optional. /// The MusicBrainz identifier of the release group. Optional. /// The MusicBrainz identifier of the release artist. Optional. @@ -27,10 +29,13 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Album /// The list of tracks of the album. Required. [DebuggerDisplay("Title: {Metadata.Title}")] public record AddAlbumRequest( - AlbumMetadataDto? Metadata, + MusicAlbumMetadataDto? Metadata, MusicMediaFormat? MediaFormat, + MusicReleasePackaging? Packaging, string? Barcode, - string? CatalogNumber, + List? CatalogNumbers, + string? Label, + string? ASIN, Guid? MusicBrainzReleaseId, Guid? MusicBrainzReleaseGroupId, Guid? MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequest.cs index c7c95a70..b79b4816 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequest.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; @@ -16,8 +15,11 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Album /// /// The album metadata of the album. Required. /// The physical or digital medium of the album. Optional. +/// The outermost physical packaging of the album. Optional. /// The barcode of the album. Optional. -/// The catalog number of the album. Optional. +/// The catalog numbers of the album. Optional. +/// The name of the label that issued the album. Optional. +/// The ASIN (Amazon Standard Identification Number) of the album. Optional. /// The MusicBrainz identifier of the release. Optional. /// The MusicBrainz identifier of the release group. Optional. /// The MusicBrainz identifier of the release artist. Optional. @@ -25,10 +27,13 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Album /// The list of ratings for this album. Required. [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateAlbumRequest( - AlbumMetadataDto? Metadata, + MusicAlbumMetadataDto? Metadata, MusicMediaFormat? MediaFormat, + MusicReleasePackaging? Packaging, string? Barcode, - string? CatalogNumber, + List? CatalogNumbers, + string? Label, + string? ASIN, Guid? MusicBrainzReleaseId, Guid? MusicBrainzReleaseGroupId, Guid? MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequest.cs index 53d76617..a7c32666 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequest.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using System; using System.Collections.Generic; @@ -11,16 +13,22 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artis /// /// Represents a request to add an artist, together with the albums of the artist and the tracks of those albums. /// -/// The name of the artist. Required. +/// The metadata of the artist. Required. /// The website of the artist. Optional. /// The MusicBrainz identifier of the artist. Optional. +/// The list of IPI (Interested Party Information) codes of the artist. Optional. +/// The list of ISNI (International Standard Name Identifier) codes of the artist. Optional. /// The list of media contributors that make up the artist. Required. +/// The list of ratings for the artist. Required. /// The list of albums of the artist, each with its own list of tracks. Required. -[DebuggerDisplay("Name: {Name}")] +[DebuggerDisplay("Name: {Metadata.Name}")] public record AddArtistRequest( - string? Name, + MusicArtistMetadataDto? Metadata, string? Website, Guid? MusicBrainzArtistId, + List? Ipis, + List? Isnis, List? Contributors, + List? Ratings, List? Albums ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequest.cs index 8e3b02ba..6a5cbed3 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequest.cs @@ -16,8 +16,11 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artis /// The Id of the album, when the album already exists. Optional. /// The album metadata of the album. Required. /// The physical or digital medium of the album. Optional. +/// The outermost physical packaging of the album. Optional. /// The barcode of the album. Optional. -/// The catalog number of the album. Optional. +/// The catalog numbers of the album. Optional. +/// The name of the label that issued the album. Optional. +/// The ASIN (Amazon Standard Identification Number) of the album. Optional. /// The MusicBrainz identifier of the release. Optional. /// The MusicBrainz identifier of the release group. Optional. /// The MusicBrainz identifier of the release artist. Optional. @@ -27,10 +30,13 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artis [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateArtistAlbumRequest( Guid? AlbumId, - AlbumMetadataDto? Metadata, + MusicAlbumMetadataDto? Metadata, MusicMediaFormat? MediaFormat, + MusicReleasePackaging? Packaging, string? Barcode, - string? CatalogNumber, + List? CatalogNumbers, + string? Label, + string? ASIN, Guid? MusicBrainzReleaseId, Guid? MusicBrainzReleaseGroupId, Guid? MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.cs index a300c302..12c0acf9 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -10,16 +12,22 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artis /// /// Represents a request to update an existing artist. /// -/// The name of the artist. Required. +/// The metadata of the artist. Required. /// The website of the artist. Optional. /// The MusicBrainz identifier of the artist. Optional. +/// The list of IPI (Interested Party Information) codes of the artist. Optional. +/// The list of ISNI (International Standard Name Identifier) codes of the artist. Optional. /// The list of media contributors that make up the artist. Required. +/// The list of ratings for the artist. Required. /// The list of albums of the artist, each with its own list of tracks. Required. -[DebuggerDisplay("Name: {Name}")] +[DebuggerDisplay("Name: {Metadata.Name}")] public record UpdateArtistRequest( - string? Name, + MusicArtistMetadataDto? Metadata, string? Website, Guid? MusicBrainzArtistId, + List? Ipis, + List? Isnis, List? Contributors, + List? Ratings, List? Albums ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequest.cs index 2b7a10a2..6831cdff 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequest.cs @@ -22,10 +22,9 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artis /// The script used by the language of the track. Optional. /// The musical key of the track. Optional. /// The tempo of the track in beats per minute. Optional. -/// The title of the work the track is a recording of. Optional. +/// The work the track is a recording of. Optional. /// The MusicBrainz identifier of the recording. Optional. /// The MusicBrainz identifier of the track. Optional. -/// The MusicBrainz identifier of the work. Optional. /// The list of moods of the track. Optional. /// The list of ISRC (International Standard Recording Code) of the track. Optional. /// The list of media contributors that performed on the track. Required. @@ -34,16 +33,15 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artis public record UpdateArtistTrackRequest( Guid? TrackId, string? Path, - AudioMetadataDto? Metadata, + MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, string? Script, MusicKey? Key, int? Bpm, - string? Work, + MusicWorkDto? Work, Guid? MusicBrainzRecordingId, Guid? MusicBrainzTrackId, - Guid? MusicBrainzWorkId, List? Moods, List? Isrcs, List? Contributors, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequest.cs index 6652f6a5..328028fd 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequest.cs @@ -21,10 +21,9 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track /// The script used by the language of the track. Optional. /// The musical key of the track. Optional. /// The tempo of the track in beats per minute. Optional. -/// The title of the work the track is a recording of. Optional. +/// The work the track is a recording of. Optional. /// The MusicBrainz identifier of the recording. Optional. /// The MusicBrainz identifier of the track. Optional. -/// The MusicBrainz identifier of the work. Optional. /// The list of moods of the track. Optional. /// The list of ISRC (International Standard Recording Code) of the track. Optional. /// The list of media contributors that performed on the track. Required. @@ -32,16 +31,15 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track [DebuggerDisplay("Title: {Metadata.Title}")] public record AddTrackRequest( string? Path, - AudioMetadataDto? Metadata, + MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, string? Script, MusicKey? Key, int? Bpm, - string? Work, + MusicWorkDto? Work, Guid? MusicBrainzRecordingId, Guid? MusicBrainzTrackId, - Guid? MusicBrainzWorkId, List? Moods, List? Isrcs, List? Contributors, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs index 3a65a285..34cb73d8 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs @@ -21,10 +21,9 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track /// The script used by the language of the track. Optional. /// The musical key of the track. Optional. /// The tempo of the track in beats per minute. Optional. -/// The title of the work the track is a recording of. Optional. +/// The work the track is a recording of. Optional. /// The MusicBrainz identifier of the recording. Optional. /// The MusicBrainz identifier of the track. Optional. -/// The MusicBrainz identifier of the work. Optional. /// The list of moods of the track. Optional. /// The list of ISRC (International Standard Recording Code) of the track. Optional. /// The list of media contributors that performed on the track. Required. @@ -32,16 +31,15 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateTrackRequest( string? Path, - AudioMetadataDto? Metadata, + MusicTrackMetadataDto? Metadata, int? TrackNumber, int? DiscNumber, string? Script, MusicKey? Key, int? Bpm, - string? Work, + MusicWorkDto? Work, Guid? MusicBrainzRecordingId, Guid? MusicBrainzTrackId, - Guid? MusicBrainzWorkId, List? Moods, List? Isrcs, List? Contributors, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs index df43eb8d..8f8e7196 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs @@ -16,6 +16,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// Whether this media library should update the metadata of its elements from the web, or not. Optional. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. +/// The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent. [DebuggerDisplay("Title: {Title}")] public record AddLibraryRequest( string? Title, @@ -26,5 +27,6 @@ public record AddLibraryRequest( bool IsLocked, bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, - bool ShouldSkipUnchangedDirectoriesDuringScan + bool ShouldSkipUnchangedDirectoriesDuringScan, + LibraryPathTemplatePartRequest[]? PathTemplateParts ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequest.cs new file mode 100644 index 00000000..41c8557c --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.Management; + +/// +/// Represents a request to get the path parts available for a media library type. +/// +/// The media library type whose available path parts are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryPathTemplatePartsRequest( + string? LibraryType +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequest.cs new file mode 100644 index 00000000..bb4fab5e --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.Management; + +/// +/// Represents one part of the path template of a media library. +/// +/// The kind of the path part. Required. +/// The literal text or the value mask of the path part. Optional for separators, required otherwise. +/// Whether the path part can be absent from the path. Optional. +[DebuggerDisplay("Kind: {Kind}; Representation: {Representation}")] +public record LibraryPathTemplatePartRequest( + string? Kind, + string? Representation, + bool IsOptional +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs index 9590f10a..ba3b9226 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs @@ -19,6 +19,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// Whether this media library should update the metadata of its elements from the web, or not. Optional. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. +/// The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent. [DebuggerDisplay("Title: {Title}")] public record class UpdateLibraryRequest( Guid Id, @@ -31,5 +32,6 @@ public record class UpdateLibraryRequest( bool IsLocked, bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, - bool ShouldSkipUnchangedDirectoriesDuringScan + bool ShouldSkipUnchangedDirectoriesDuringScan, + LibraryPathTemplatePartRequest[]? PathTemplateParts ); diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs index 34c12869..f42474fa 100644 --- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs @@ -12,6 +12,7 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings; /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required. /// Whether the theme data served to this user is cached, or not. Required. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required. +/// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. Required. /// Whether PDF books are rendered as page images for the user, or not. Required. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. Required. [DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] @@ -21,6 +22,7 @@ public sealed record UpdateUserSettingsRequest( bool ShouldIgnoreThePrefixForAlphaPicker, bool IsThemeCachingEnabled, bool ShouldAggregateMetadataWhenMissing, + bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, bool ShouldPreserveBookStyles ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs index e71a8bef..84760c8f 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs @@ -19,8 +19,11 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albu /// The Id of the media library this album belongs to. /// The album metadata of the album. /// The physical or digital medium of the album, if applicable. +/// The outermost physical packaging of the album, if applicable. /// The barcode of the album, if applicable. -/// The catalog number of the album, if applicable. +/// The catalog numbers of the album, if applicable. +/// The name of the label that issued the album, if applicable. +/// The ASIN (Amazon Standard Identification Number) of the album, if applicable. /// The MusicBrainz identifier of the release, if applicable. /// The MusicBrainz identifier of the release group, if applicable. /// The MusicBrainz identifier of the release artist, if applicable. @@ -34,10 +37,13 @@ public record AlbumResponse( Guid Id, Guid ArtistId, Guid LibraryId, - AlbumMetadataDto Metadata, + MusicAlbumMetadataDto Metadata, MusicMediaFormat? MediaFormat, + MusicReleasePackaging? Packaging, string? Barcode, - string? CatalogNumber, + List? CatalogNumbers, + string? Label, + string? ASIN, Guid? MusicBrainzReleaseId, Guid? MusicBrainzReleaseGroupId, Guid? MusicBrainzReleaseArtistId, diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponse.cs index 6cd9d3d0..ec147700 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponse.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using System; using System.Collections.Generic; @@ -13,22 +15,28 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Arti /// /// The Id of the artist. /// The Id of the media library this artist belongs to. -/// The name of the artist. +/// The metadata of the artist. /// The website of the artist, if applicable. /// The MusicBrainz identifier of the artist, if applicable. -/// The list of references to the media contributors that make up the artist, each with the role they played. -/// The list of albums of the artist, each with its own list of tracks. +/// The list of IPI (Interested Party Information) codes of the artist. +/// The list of ISNI (International Standard Name Identifier) codes of the artist. /// The date and time when the artist was created. /// The optional date and time when the artist was updated. -[DebuggerDisplay("Name: {Name}")] +/// The list of references to the media contributors that make up the artist, each with the role they played. +/// The list of ratings for this artist. +/// The list of albums of the artist, each with its own list of tracks. +[DebuggerDisplay("Name: {Metadata.Name}")] public record ArtistResponse( Guid Id, Guid LibraryId, - string Name, + MusicArtistMetadataDto Metadata, string? Website, Guid? MusicBrainzArtistId, - List? Contributors, - List? Albums, + List? Ipis, + List? Isnis, DateTime CreatedOnUtc, - DateTime? UpdatedOnUtc + DateTime? UpdatedOnUtc, + List? Contributors, + List? Ratings, + List? Albums ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs index 72fd1ddb..b6e64f64 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs @@ -24,10 +24,9 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Trac /// The script used by the language of the track, if applicable. /// The musical key of the track, if applicable. /// The tempo of the track in beats per minute, if applicable. -/// The title of the work the track is a recording of, if applicable. +/// The work the track is a recording of, if applicable. /// The MusicBrainz identifier of the recording, if applicable. /// The MusicBrainz identifier of the track, if applicable. -/// The MusicBrainz identifier of the work, if applicable. /// The date and time when the track was created. /// The optional date and time when the track was updated. /// The list of moods of the track. @@ -40,16 +39,15 @@ public record TrackResponse( Guid AlbumId, Guid LibraryId, string Path, - AudioMetadataDto Metadata, + MusicTrackMetadataDto Metadata, int TrackNumber, int? DiscNumber, string? Script, MusicKey? Key, int? Bpm, - string? Work, + MusicWorkDto? Work, Guid? MusicBrainzRecordingId, Guid? MusicBrainzTrackId, - Guid? MusicBrainzWorkId, DateTime CreatedOnUtc, DateTime? UpdatedOnUtc, List? Moods, diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponse.cs new file mode 100644 index 00000000..43e7966c --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponse.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.Management; + +/// +/// Represents a path part definition response. +/// +/// The kind of the path part. +/// The value type captured by the path part. +/// The default representation of the path part, pre-filled when it is added to a template. +/// Whether the path part is optional by default. +[DebuggerDisplay("Kind: {Kind}; ValueType: {ValueType}")] +public record LibraryPathPartDefinitionResponse( + string Kind, + string ValueType, + string DefaultRepresentation, + bool IsOptionalByDefault +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponse.cs new file mode 100644 index 00000000..91434a61 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponse.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.Management; + +/// +/// Represents a path template catalog response. +/// +/// The path parts that can be used in the path template of the library type. +/// The ordered parts of the default path template of the library type, describing the ideal structure the application expects. +[DebuggerDisplay("Parts: {Parts.Count}; DefaultTemplateParts: {DefaultTemplateParts.Count}")] +public record LibraryPathTemplateCatalogResponse( + List Parts, + List DefaultTemplateParts +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponse.cs new file mode 100644 index 00000000..b48e2e2a --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.Management; + +/// +/// Represents a path template part response. +/// +/// The kind of the path part. +/// The literal text or the value mask of the path part. +/// Whether the path part can be absent from the path. +[DebuggerDisplay("Kind: {Kind}; Representation: {Representation}")] +public record LibraryPathTemplatePartResponse( + string Kind, + string Representation, + bool IsOptional +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs index 9dff6ddc..63e17fb0 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs @@ -21,6 +21,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// Whether the media library should update the metadata of its elements from the web, or not. /// Whether the media library should copy the downloaded metadata into the media library content locations, or not. /// Whether the media library should skip the directories whose contents have not changed since the last scan, during the scan. +/// The ordered parts of the template describing the structure of the media library on disk. /// The date and time when the library was created. /// The optional date and time when the library was updated. [DebuggerDisplay("Title: {Title}")] @@ -36,6 +37,7 @@ public record LibraryResponse( bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan, + List PathTemplateParts, DateTime CreatedOnUtc, DateTime? UpdatedOnUtc ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs index 97d9a8e3..b8111399 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs @@ -3,6 +3,7 @@ using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs index 0db9b39e..11bdbf60 100644 --- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs @@ -14,6 +14,7 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings; /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. +/// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. [DebuggerDisplay("UserId: {UserId}")] @@ -24,6 +25,7 @@ public sealed record UserSettingsResponse( bool ShouldIgnoreThePrefixForAlphaPicker, bool IsThemeCachingEnabled, bool ShouldAggregateMetadataWhenMissing, + bool ShouldAggregateArtworkWhenMissing, bool ShouldRenderPdfAsImages, bool ShouldPreserveBookStyles ); diff --git a/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs index dcfc6aa0..29e95f2f 100644 --- a/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; @@ -39,73 +40,96 @@ public class AlbumConfiguration : IEntityTypeConfiguration builder.Property(album => album.OriginalTitle) .HasMaxLength(255) .HasColumnOrder(4); + builder.Property(album => album.ReleaseTitle) + .HasMaxLength(255) + .HasColumnOrder(26); builder.Property(album => album.Description) .HasMaxLength(2000) .HasColumnOrder(5); - builder.Property(album => album.OriginalReleaseDate) + builder.Property(album => album.Disambiguation) + .HasMaxLength(255) .HasColumnOrder(6); - builder.Property(album => album.OriginalReleaseYear) + builder.Property(album => album.OriginalReleaseDate) .HasColumnOrder(7); - builder.Property(album => album.ReReleaseDate) + builder.Property(album => album.OriginalReleaseYear) .HasColumnOrder(8); - builder.Property(album => album.ReReleaseYear) + builder.Property(album => album.ReReleaseDate) .HasColumnOrder(9); + builder.Property(album => album.ReReleaseYear) + .HasColumnOrder(10); builder.Property(album => album.ReleaseCountry) .HasConversion() .HasMaxLength(2) - .HasColumnOrder(10); - builder.Property(album => album.ReleaseVersion) .HasColumnOrder(11); - builder.Property(album => album.LanguageCode) + builder.Property(album => album.ReleaseVersion) .HasColumnOrder(12); - builder.Property(album => album.LanguageName) + builder.Property(album => album.LanguageCode) .HasColumnOrder(13); - builder.Property(album => album.LanguageNativeName) + builder.Property(album => album.LanguageName) .HasColumnOrder(14); - builder.Property(album => album.OriginalLanguageCode) + builder.Property(album => album.LanguageNativeName) .HasColumnOrder(15); - builder.Property(album => album.OriginalLanguageName) + builder.Property(album => album.OriginalLanguageCode) .HasColumnOrder(16); - builder.Property(album => album.OriginalLanguageNativeName) + builder.Property(album => album.OriginalLanguageName) .HasColumnOrder(17); - builder.Property(album => album.ReleaseType) - .HasConversion() - .HasMaxLength(50) + builder.Property(album => album.OriginalLanguageNativeName) .HasColumnOrder(18); + builder.Property(album => album.Script) + .HasMaxLength(50) + .HasColumnOrder(19); builder.Property(album => album.ReleaseStatus) .HasConversion() .HasMaxLength(50) - .HasColumnOrder(19); - builder.Property(album => album.TotalDiscs) .HasColumnOrder(20); - builder.Property(album => album.TotalTracks) + builder.Property(album => album.TotalDiscs) .HasColumnOrder(21); + builder.Property(album => album.TotalTracks) + .HasColumnOrder(22); builder.Property(album => album.MediaFormat) .HasConversion() .HasMaxLength(50) - .HasColumnOrder(22); - builder.Property(album => album.Barcode) - .HasMaxLength(13) .HasColumnOrder(23); - builder.Property(album => album.CatalogNumber) + builder.Property(album => album.Packaging) + .HasConversion() .HasMaxLength(50) .HasColumnOrder(24); - builder.Property(album => album.MusicBrainzReleaseId) + builder.Property(album => album.Barcode) + .HasMaxLength(13) .HasColumnOrder(25); - builder.Property(album => album.MusicBrainzReleaseGroupId) - .HasColumnOrder(26); - builder.Property(album => album.MusicBrainzReleaseArtistId) + builder.Property(album => album.Label) + .HasMaxLength(255) .HasColumnOrder(27); + builder.Property(album => album.ASIN) + .HasMaxLength(20) + .HasColumnOrder(28); + builder.Property(album => album.MusicBrainzReleaseId) + .HasColumnOrder(29); + builder.Property(album => album.MusicBrainzReleaseGroupId) + .HasColumnOrder(30); + builder.Property(album => album.MusicBrainzReleaseArtistId) + .HasColumnOrder(31); builder.Property(album => album.CreatedOnUtc) .IsRequired() - .HasColumnOrder(28); + .HasColumnOrder(32); builder.Property(album => album.CreatedBy) .IsRequired() - .HasColumnOrder(29); + .HasColumnOrder(33); builder.Property(album => album.UpdatedOnUtc) - .HasColumnOrder(30); + .HasColumnOrder(34); builder.Property(album => album.UpdatedBy) - .HasColumnOrder(31); + .HasColumnOrder(35); + builder.Property(album => album.MetadataStatus) + .HasConversion() + .HasMaxLength(20) + .IsRequired() + .HasDefaultValue(MetadataStatus.Pending) + .HasColumnOrder(36); + builder.Property(album => album.LastMetadataUpdateUtc) + .HasColumnOrder(37); + builder.Property(album => album.MetadataProvider) + .HasMaxLength(100) + .HasColumnOrder(38); builder.HasOne(album => album.Artist) .WithMany(artist => artist.Albums) @@ -146,6 +170,35 @@ public class AlbumConfiguration : IEntityTypeConfiguration j.ToTable("AlbumGenres"); }); + builder.OwnsMany(album => album.ReleaseTypes, releaseTypeBuilder => + { + releaseTypeBuilder.ToTable("AlbumReleaseTypes"); + releaseTypeBuilder.WithOwner() + .HasForeignKey("AlbumId"); + releaseTypeBuilder.Property("Id") + .ValueGeneratedOnAdd(); + releaseTypeBuilder.HasKey("Id"); + + releaseTypeBuilder.Property(releaseType => releaseType.ReleaseType) + .HasConversion() + .HasMaxLength(50) + .IsRequired(); + }); + + builder.OwnsMany(album => album.CatalogNumbers, catalogNumberBuilder => + { + catalogNumberBuilder.ToTable("AlbumCatalogNumbers"); + catalogNumberBuilder.WithOwner() + .HasForeignKey("AlbumId"); + catalogNumberBuilder.Property("Id") + .ValueGeneratedOnAdd(); + catalogNumberBuilder.HasKey("Id"); + + catalogNumberBuilder.Property(catalogNumber => catalogNumber.CatalogNumber) + .HasMaxLength(50) + .IsRequired(); + }); + builder.OwnsMany(album => album.Ratings, ratingBuilder => { ratingBuilder.ToTable("AlbumRatings"); diff --git a/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs index 530f6917..a4a63eb7 100644 --- a/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs @@ -1,8 +1,11 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; +using System.Collections.Generic; #endregion namespace Lumina.DataAccess.Common.Configuration; @@ -31,21 +34,168 @@ public class ArtistConfiguration : IEntityTypeConfiguration .IsRequired() .HasMaxLength(255) .HasColumnOrder(2); + builder.Property(artist => artist.SortName) + .HasMaxLength(255) + .HasColumnOrder(3); + builder.Property(artist => artist.Disambiguation) + .HasMaxLength(255) + .HasColumnOrder(4); + builder.Property(artist => artist.Type) + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(5); + builder.Property(artist => artist.Gender) + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(6); + builder.Property(artist => artist.Country) + .HasMaxLength(2) + .HasColumnOrder(7); + builder.Property(artist => artist.LifeSpanBegin) + .HasColumnOrder(8); + builder.Property(artist => artist.LifeSpanEnd) + .HasColumnOrder(9); + builder.Property(artist => artist.IsEnded) + .HasColumnOrder(10); builder.Property(artist => artist.Website) .HasMaxLength(2048) - .HasColumnOrder(3); + .HasColumnOrder(11); builder.Property(artist => artist.MusicBrainzArtistId) - .HasColumnOrder(4); + .HasColumnOrder(12); builder.Property(artist => artist.CreatedOnUtc) .IsRequired() - .HasColumnOrder(5); + .HasColumnOrder(13); builder.Property(artist => artist.CreatedBy) .IsRequired() - .HasColumnOrder(6); + .HasColumnOrder(14); builder.Property(artist => artist.UpdatedOnUtc) - .HasColumnOrder(7); + .HasColumnOrder(15); builder.Property(artist => artist.UpdatedBy) - .HasColumnOrder(8); + .HasColumnOrder(16); + builder.Property(artist => artist.MetadataStatus) + .HasConversion() + .HasMaxLength(20) + .IsRequired() + .HasDefaultValue(MetadataStatus.Pending) + .HasColumnOrder(17); + builder.Property(artist => artist.LastMetadataUpdateUtc) + .HasColumnOrder(18); + builder.Property(artist => artist.MetadataProvider) + .HasMaxLength(100) + .HasColumnOrder(19); + + // The areas are owned value objects that are never referenced on their own, so they are stored as JSON documents next to the artist. + builder.OwnsOne(artist => artist.Area, areaBuilder => areaBuilder.ToJson()); + builder.OwnsOne(artist => artist.BeginArea, beginAreaBuilder => beginAreaBuilder.ToJson()); + builder.OwnsOne(artist => artist.EndArea, endAreaBuilder => endAreaBuilder.ToJson()); + + builder.OwnsMany(artist => artist.Aliases, aliasBuilder => + { + aliasBuilder.ToTable("ArtistAliases"); + aliasBuilder.WithOwner() + .HasForeignKey("ArtistId"); + aliasBuilder.Property("Id") + .ValueGeneratedOnAdd(); + aliasBuilder.HasKey("Id"); + + aliasBuilder.Property(alias => alias.Name) + .IsRequired() + .HasMaxLength(255); + aliasBuilder.Property(alias => alias.SortName) + .HasMaxLength(255); + aliasBuilder.Property(alias => alias.Type) + .HasMaxLength(50); + aliasBuilder.Property(alias => alias.Locale) + .HasMaxLength(20); + }); + + builder.OwnsMany(artist => artist.Ipis, ipiBuilder => + { + ipiBuilder.ToTable("ArtistIpis"); + ipiBuilder.WithOwner() + .HasForeignKey("ArtistId"); + ipiBuilder.Property("Id") + .ValueGeneratedOnAdd(); + ipiBuilder.HasKey("Id"); + + ipiBuilder.Property(ipi => ipi.Value) + .IsRequired() + .HasMaxLength(20); + }); + + builder.OwnsMany(artist => artist.Isnis, isniBuilder => + { + isniBuilder.ToTable("ArtistIsnis"); + isniBuilder.WithOwner() + .HasForeignKey("ArtistId"); + isniBuilder.Property("Id") + .ValueGeneratedOnAdd(); + isniBuilder.HasKey("Id"); + + isniBuilder.Property(isni => isni.Value) + .IsRequired() + .HasMaxLength(20); + }); + + // since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates, + // we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key + builder.HasMany(artist => artist.Tags) + .WithMany() + .UsingEntity>( + "ArtistTags", + j => j.HasOne() + .WithMany() + .HasForeignKey("TagId"), + j => j.HasOne() + .WithMany() + .HasForeignKey("ArtistId"), + j => + { + j.HasKey("ArtistId", "TagId"); + j.ToTable("ArtistTags"); + }); + + builder.HasMany(artist => artist.Genres) + .WithMany() + .UsingEntity>( + "ArtistGenres", + j => j.HasOne() + .WithMany() + .HasForeignKey("GenreId"), + j => j.HasOne() + .WithMany() + .HasForeignKey("ArtistId"), + j => + { + j.HasKey("ArtistId", "GenreId"); + j.ToTable("ArtistGenres"); + }); + + builder.OwnsMany(artist => artist.Ratings, ratingBuilder => + { + ratingBuilder.ToTable("ArtistRatings"); + ratingBuilder.WithOwner() + .HasForeignKey("ArtistId"); + ratingBuilder.Property("Id") + .ValueGeneratedOnAdd(); + ratingBuilder.HasKey("Id"); + + ratingBuilder.Property(rating => rating.Value) + .HasColumnType("decimal(3,2)") + .IsRequired(); + + ratingBuilder.Property(rating => rating.MaxValue) + .HasColumnType("decimal(3,2)") + .IsRequired(); + + ratingBuilder.Property(rating => rating.VoteCount) + .IsRequired(false); + + ratingBuilder.Property(rating => rating.Source) + .HasConversion() + .HasMaxLength(50) + .IsRequired(false); + }); builder.HasMany(artist => artist.Contributors) .WithOne() diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs index 5f20f98a..ae9fcc88 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -66,6 +66,11 @@ public class LibraryConfiguration : IEntityTypeConfiguration .HasDefaultValue(null) .HasColumnOrder(10); + builder.Property(library => library.PathTemplateFingerprint) + .HasMaxLength(64) + .HasDefaultValue(null) + .HasColumnOrder(11); + // one user with many libraries builder.HasOne(library => library.User) .WithMany(user => user.Libraries) @@ -95,21 +100,48 @@ public class LibraryConfiguration : IEntityTypeConfiguration .IsRequired(); }); + // the path template parts are ordered, so their position is stored explicitly and part of a unique index together with the library + builder.OwnsMany(library => library.PathTemplateParts, partBuilder => + { + partBuilder.ToTable("LibraryPathTemplateParts"); + partBuilder.WithOwner() + .HasForeignKey("LibraryId"); + + partBuilder.Property("Id") + .ValueGeneratedOnAdd(); + partBuilder.HasKey("Id"); + partBuilder.HasIndex("LibraryId", nameof(LibraryPathTemplatePartEntity.Position)) + .IsUnique(); + + partBuilder.Property(part => part.Position) + .HasColumnName("Position") + .IsRequired(); + partBuilder.Property(part => part.Kind) + .HasConversion() + .HasMaxLength(32) + .IsRequired(); + partBuilder.Property(part => part.Representation) + .HasMaxLength(512) + .IsRequired(); + partBuilder.Property(part => part.IsOptional) + .IsRequired(); + }); + // audit builder.Property(library => library.CreatedOnUtc) .IsRequired() - .HasColumnOrder(11); + .HasColumnOrder(12); builder.Property(library => library.CreatedBy) .IsRequired() - .HasColumnOrder(12); + .HasColumnOrder(13); builder.Property(library => library.UpdatedOnUtc) .HasDefaultValue(null) - .HasColumnOrder(13); + .HasColumnOrder(14); builder.Property(library => library.UpdatedBy) .HasDefaultValue(null) - .HasColumnOrder(14); + .HasColumnOrder(15); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs new file mode 100644 index 00000000..50853c1b --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class MusicArtworkConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("MusicArtwork"); + builder.HasKey(musicArtwork => musicArtwork.Id); + builder.Property(musicArtwork => musicArtwork.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + builder.Property(musicArtwork => musicArtwork.OwnerType) + .IsRequired() + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(1); + builder.Property(musicArtwork => musicArtwork.OwnerId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(musicArtwork => musicArtwork.ArtworkType) + .IsRequired() + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(3); + builder.Property(musicArtwork => musicArtwork.Ordinal) + .IsRequired() + .HasColumnOrder(4); + builder.Property(musicArtwork => musicArtwork.FileName) + .HasMaxLength(2048) + .HasColumnOrder(5); + builder.Property(musicArtwork => musicArtwork.ContentHash) + .HasColumnOrder(6); + builder.Property(musicArtwork => musicArtwork.Status) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(7); + builder.Property(musicArtwork => musicArtwork.Provider) + .HasMaxLength(100) + .HasColumnOrder(8); + builder.Property(musicArtwork => musicArtwork.LastUpdateUtc) + .HasColumnOrder(9); + + // audit + builder.Property(musicArtwork => musicArtwork.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(10); + + builder.Property(musicArtwork => musicArtwork.CreatedBy) + .IsRequired() + .HasColumnOrder(11); + + builder.Property(musicArtwork => musicArtwork.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(12); + + builder.Property(musicArtwork => musicArtwork.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(13); + + builder.HasIndex(musicArtwork => new { musicArtwork.OwnerType, musicArtwork.OwnerId, musicArtwork.ArtworkType, musicArtwork.Ordinal }) + .IsUnique(); + builder.HasIndex(musicArtwork => musicArtwork.Status); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs new file mode 100644 index 00000000..7cc8aa53 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/MusicLibraryScanItemMetadataConfiguration.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("MusicLibraryScanItemMetadata"); + builder.HasKey(musicMetadata => musicMetadata.Id); + builder.Property(musicMetadata => musicMetadata.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + builder.Property(musicMetadata => musicMetadata.LibraryScanId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(musicMetadata => musicMetadata.LibraryId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(musicMetadata => musicMetadata.Path) + .IsRequired() + .HasMaxLength(2048) + .HasColumnOrder(3); + builder.Property(musicMetadata => musicMetadata.ArtistName) + .HasMaxLength(255) + .HasColumnOrder(4); + builder.Property(musicMetadata => musicMetadata.ReleaseType) + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(5); + builder.Property(musicMetadata => musicMetadata.ReleaseYear) + .HasColumnOrder(6); + builder.Property(musicMetadata => musicMetadata.ReleaseName) + .HasMaxLength(255) + .HasColumnOrder(7); + builder.Property(musicMetadata => musicMetadata.TrackTitle) + .HasMaxLength(255) + .HasColumnOrder(8); + builder.Property(musicMetadata => musicMetadata.TrackNumber) + .HasColumnOrder(9); + builder.Property(musicMetadata => musicMetadata.DiscNumber) + .HasColumnOrder(10); + builder.Property(musicMetadata => musicMetadata.DurationInSeconds) + .HasColumnOrder(11); + builder.Property(musicMetadata => musicMetadata.SampleRate) + .HasColumnOrder(12); + builder.Property(musicMetadata => musicMetadata.Channels) + .HasColumnOrder(13); + builder.Property(musicMetadata => musicMetadata.BitDepth) + .HasColumnOrder(14); + builder.Property(musicMetadata => musicMetadata.AudioCodec) + .HasMaxLength(50) + .HasColumnOrder(15); + builder.Property(musicMetadata => musicMetadata.Bitrate) + .HasColumnOrder(16); + builder.Property(musicMetadata => musicMetadata.MusicBrainzArtistId) + .HasColumnOrder(17); + builder.Property(musicMetadata => musicMetadata.MusicBrainzReleaseArtistId) + .HasColumnOrder(18); + builder.Property(musicMetadata => musicMetadata.MusicBrainzReleaseGroupId) + .HasColumnOrder(19); + builder.Property(musicMetadata => musicMetadata.MusicBrainzReleaseId) + .HasColumnOrder(20); + builder.Property(musicMetadata => musicMetadata.MusicBrainzRecordingId) + .HasColumnOrder(21); + builder.Property(musicMetadata => musicMetadata.MusicBrainzTrackId) + .HasColumnOrder(22); + builder.Property(musicMetadata => musicMetadata.MusicBrainzWorkId) + .HasColumnOrder(23); + builder.Property(musicMetadata => musicMetadata.WorkTitle) + .HasMaxLength(255) + .HasColumnOrder(24); + builder.Property(musicMetadata => musicMetadata.AcoustId) + .HasMaxLength(64) + .HasColumnOrder(25); + builder.Property(musicMetadata => musicMetadata.ReplayGainTrackGain) + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + builder.Property(musicMetadata => musicMetadata.ReplayGainTrackPeak) + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + builder.Property(musicMetadata => musicMetadata.ReplayGainAlbumGain) + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + builder.Property(musicMetadata => musicMetadata.ReplayGainAlbumPeak) + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + builder.PrimitiveCollection(musicMetadata => musicMetadata.Moods) + .HasColumnOrder(30); + + builder.HasIndex(musicMetadata => new { musicMetadata.LibraryScanId, musicMetadata.Path }) + .IsUnique(); // the metadata of the same physical file cannot be staged twice during the same scan + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs index c32b2194..733def1b 100644 --- a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; @@ -46,77 +47,111 @@ public class TrackConfiguration : IEntityTypeConfiguration builder.Property(track => track.Description) .HasMaxLength(2000) .HasColumnOrder(6); - builder.Property(track => track.OriginalReleaseDate) + builder.Property(track => track.Disambiguation) + .HasMaxLength(255) .HasColumnOrder(7); - builder.Property(track => track.OriginalReleaseYear) + builder.Property(track => track.OriginalReleaseDate) .HasColumnOrder(8); - builder.Property(track => track.ReReleaseDate) + builder.Property(track => track.OriginalReleaseYear) .HasColumnOrder(9); - builder.Property(track => track.ReReleaseYear) + builder.Property(track => track.ReReleaseDate) .HasColumnOrder(10); + builder.Property(track => track.ReReleaseYear) + .HasColumnOrder(11); builder.Property(track => track.ReleaseCountry) .HasConversion() .HasMaxLength(2) - .HasColumnOrder(11); - builder.Property(track => track.ReleaseVersion) .HasColumnOrder(12); - builder.Property(track => track.LanguageCode) + builder.Property(track => track.ReleaseVersion) .HasColumnOrder(13); - builder.Property(track => track.LanguageName) + builder.Property(track => track.LanguageCode) .HasColumnOrder(14); - builder.Property(track => track.LanguageNativeName) + builder.Property(track => track.LanguageName) .HasColumnOrder(15); - builder.Property(track => track.OriginalLanguageCode) + builder.Property(track => track.LanguageNativeName) .HasColumnOrder(16); - builder.Property(track => track.OriginalLanguageName) + builder.Property(track => track.OriginalLanguageCode) .HasColumnOrder(17); - builder.Property(track => track.OriginalLanguageNativeName) + builder.Property(track => track.OriginalLanguageName) .HasColumnOrder(18); - builder.Property(track => track.DurationInSeconds) + builder.Property(track => track.OriginalLanguageNativeName) .HasColumnOrder(19); - builder.Property(track => track.SampleRate) + builder.Property(track => track.DurationInSeconds) .HasColumnOrder(20); - builder.Property(track => track.Channels) + builder.Property(track => track.SampleRate) .HasColumnOrder(21); - builder.Property(track => track.BitDepth) + builder.Property(track => track.Channels) .HasColumnOrder(22); + builder.Property(track => track.BitDepth) + .HasColumnOrder(23); builder.Property(track => track.AudioCodec) .HasMaxLength(50) - .HasColumnOrder(23); - builder.Property(track => track.Bitrate) .HasColumnOrder(24); - builder.Property(track => track.TrackNumber) + builder.Property(track => track.Bitrate) .HasColumnOrder(25); - builder.Property(track => track.DiscNumber) + builder.Property(track => track.TrackNumber) .HasColumnOrder(26); + builder.Property(track => track.DiscNumber) + .HasColumnOrder(27); builder.Property(track => track.Script) .HasMaxLength(50) - .HasColumnOrder(27); + .HasColumnOrder(28); builder.Property(track => track.Key) .HasConversion() .HasMaxLength(50) - .HasColumnOrder(28); - builder.Property(track => track.Bpm) .HasColumnOrder(29); - builder.Property(track => track.Work) - .HasMaxLength(255) + builder.Property(track => track.Bpm) .HasColumnOrder(30); - builder.Property(track => track.MusicBrainzRecordingId) + builder.Property(track => track.IsVideo) .HasColumnOrder(31); - builder.Property(track => track.MusicBrainzTrackId) + builder.Property(track => track.WorkTitle) + .HasMaxLength(255) .HasColumnOrder(32); - builder.Property(track => track.MusicBrainzWorkId) + builder.Property(track => track.WorkType) + .HasMaxLength(50) .HasColumnOrder(33); + builder.Property(track => track.MusicBrainzRecordingId) + .HasColumnOrder(34); + builder.Property(track => track.MusicBrainzTrackId) + .HasColumnOrder(35); + builder.Property(track => track.MusicBrainzWorkId) + .HasColumnOrder(36); builder.Property(track => track.CreatedOnUtc) .IsRequired() - .HasColumnOrder(34); + .HasColumnOrder(37); builder.Property(track => track.CreatedBy) .IsRequired() - .HasColumnOrder(35); + .HasColumnOrder(38); builder.Property(track => track.UpdatedOnUtc) - .HasColumnOrder(36); + .HasColumnOrder(39); builder.Property(track => track.UpdatedBy) - .HasColumnOrder(37); + .HasColumnOrder(40); + builder.Property(track => track.MetadataStatus) + .HasConversion() + .HasMaxLength(20) + .IsRequired() + .HasDefaultValue(MetadataStatus.Pending) + .HasColumnOrder(41); + builder.Property(track => track.LastMetadataUpdateUtc) + .HasColumnOrder(42); + builder.Property(track => track.MetadataProvider) + .HasMaxLength(100) + .HasColumnOrder(43); + builder.Property(track => track.AcoustId) + .HasMaxLength(64) + .HasColumnOrder(44); + builder.Property(track => track.ReplayGainTrackGain) + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + builder.Property(track => track.ReplayGainTrackPeak) + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + builder.Property(track => track.ReplayGainAlbumGain) + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + builder.Property(track => track.ReplayGainAlbumPeak) + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); builder.HasOne(track => track.Album) .WithMany(album => album.Tracks) @@ -186,6 +221,39 @@ public class TrackConfiguration : IEntityTypeConfiguration .IsRequired(); }); + builder.OwnsMany(track => track.WorkLanguages, workLanguageBuilder => + { + workLanguageBuilder.ToTable("TrackWorkLanguages"); + workLanguageBuilder.WithOwner() + .HasForeignKey("TrackId"); + workLanguageBuilder.Property("Id") + .ValueGeneratedOnAdd(); + workLanguageBuilder.HasKey("Id"); + + workLanguageBuilder.Property(workLanguage => workLanguage.LanguageCode) + .IsRequired() + .HasMaxLength(5); + workLanguageBuilder.Property(workLanguage => workLanguage.LanguageName) + .IsRequired() + .HasMaxLength(100); + workLanguageBuilder.Property(workLanguage => workLanguage.NativeName) + .HasMaxLength(100); + }); + + builder.OwnsMany(track => track.WorkIswcs, workIswcBuilder => + { + workIswcBuilder.ToTable("TrackWorkIswcs"); + workIswcBuilder.WithOwner() + .HasForeignKey("TrackId"); + workIswcBuilder.Property("Id") + .ValueGeneratedOnAdd(); + workIswcBuilder.HasKey("Id"); + + workIswcBuilder.Property(workIswc => workIswc.Value) + .HasMaxLength(20) + .IsRequired(); + }); + builder.HasMany(track => track.Contributors) .WithOne() .HasForeignKey(contributor => contributor.TrackId) diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs index 3e88f89f..d6713dc8 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs @@ -50,6 +50,10 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration settings.ShouldAggregateArtworkWhenMissing) + .IsRequired() + .HasColumnOrder(13); + builder.Property(settings => settings.ShouldRenderPdfAsImages) .IsRequired() .HasColumnOrder(11); diff --git a/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.cs b/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.cs index b87a0278..9f01283b 100644 --- a/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.cs +++ b/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.cs @@ -11,9 +11,7 @@ namespace Lumina.DataAccess.Common.Migrations /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.DropIndex( - name: "IX_BookContributors_BookId_MediaContributorId", - table: "BookContributors"); + migrationBuilder.Sql("DROP INDEX IF EXISTS \"IX_BookContributors_BookId_MediaContributorId\";"); migrationBuilder.DropColumn( name: "RoleName", diff --git a/src/Lumina.DataAccess/Common/Migrations/20261004113629_AddsMusicLibraryScanningAndMetadata.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261004113629_AddsMusicLibraryScanningAndMetadata.Designer.cs new file mode 100644 index 00000000..6628af98 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261004113629_AddsMusicLibraryScanningAndMetadata.Designer.cs @@ -0,0 +1,3381 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261004113629_AddsMusicLibraryScanningAndMetadata")] + partial class AddsMusicLibraryScanningAndMetadata + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261004113629_AddsMusicLibraryScanningAndMetadata.cs b/src/Lumina.DataAccess/Common/Migrations/20261004113629_AddsMusicLibraryScanningAndMetadata.cs new file mode 100644 index 00000000..a3693dea --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261004113629_AddsMusicLibraryScanningAndMetadata.cs @@ -0,0 +1,2199 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsMusicLibraryScanningAndMetadata : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.RenameColumn( + name: "Work", + table: "Tracks", + newName: "WorkTitle"); + + migrationBuilder.RenameColumn( + name: "ReleaseType", + table: "Albums", + newName: "Script"); + + migrationBuilder.RenameColumn( + name: "CatalogNumber", + table: "Albums", + newName: "Packaging"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 39) + .OldAnnotation("Relational:ColumnOrder", 36); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 40) + .OldAnnotation("Relational:ColumnOrder", 37); + + migrationBuilder.AlterColumn( + name: "TrackNumber", + table: "Tracks", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 26) + .OldAnnotation("Relational:ColumnOrder", 25); + + migrationBuilder.AlterColumn( + name: "Script", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 28) + .OldAnnotation("Relational:ColumnOrder", 27); + + migrationBuilder.AlterColumn( + name: "SampleRate", + table: "Tracks", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 21) + .OldAnnotation("Relational:ColumnOrder", 20); + + migrationBuilder.AlterColumn( + name: "ReleaseVersion", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 13) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AlterColumn( + name: "ReleaseCountry", + table: "Tracks", + type: "TEXT", + maxLength: 2, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 2, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "ReReleaseYear", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 11) + .OldAnnotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "ReReleaseDate", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateOnly), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 10) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "OriginalReleaseYear", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "OriginalReleaseDate", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateOnly), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageNativeName", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 19) + .OldAnnotation("Relational:ColumnOrder", 18); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageName", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 18) + .OldAnnotation("Relational:ColumnOrder", 17); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageCode", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 17) + .OldAnnotation("Relational:ColumnOrder", 16); + + migrationBuilder.AlterColumn( + name: "MusicBrainzWorkId", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 36) + .OldAnnotation("Relational:ColumnOrder", 33); + + migrationBuilder.AlterColumn( + name: "MusicBrainzTrackId", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 35) + .OldAnnotation("Relational:ColumnOrder", 32); + + migrationBuilder.AlterColumn( + name: "MusicBrainzRecordingId", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 34) + .OldAnnotation("Relational:ColumnOrder", 31); + + migrationBuilder.AlterColumn( + name: "LanguageNativeName", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 16) + .OldAnnotation("Relational:ColumnOrder", 15); + + migrationBuilder.AlterColumn( + name: "LanguageName", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 15) + .OldAnnotation("Relational:ColumnOrder", 14); + + migrationBuilder.AlterColumn( + name: "LanguageCode", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 14) + .OldAnnotation("Relational:ColumnOrder", 13); + + migrationBuilder.AlterColumn( + name: "Key", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 29) + .OldAnnotation("Relational:ColumnOrder", 28); + + migrationBuilder.AlterColumn( + name: "DurationInSeconds", + table: "Tracks", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 20) + .OldAnnotation("Relational:ColumnOrder", 19); + + migrationBuilder.AlterColumn( + name: "DiscNumber", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 27) + .OldAnnotation("Relational:ColumnOrder", 26); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Tracks", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 37) + .OldAnnotation("Relational:ColumnOrder", 34); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Tracks", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 38) + .OldAnnotation("Relational:ColumnOrder", 35); + + migrationBuilder.AlterColumn( + name: "Channels", + table: "Tracks", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 22) + .OldAnnotation("Relational:ColumnOrder", 21); + + migrationBuilder.AlterColumn( + name: "Bpm", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 30) + .OldAnnotation("Relational:ColumnOrder", 29); + + migrationBuilder.AlterColumn( + name: "Bitrate", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 25) + .OldAnnotation("Relational:ColumnOrder", 24); + + migrationBuilder.AlterColumn( + name: "BitDepth", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 23) + .OldAnnotation("Relational:ColumnOrder", 22); + + migrationBuilder.AlterColumn( + name: "AudioCodec", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 24) + .OldAnnotation("Relational:ColumnOrder", 23); + + migrationBuilder.AlterColumn( + name: "WorkTitle", + table: "Tracks", + type: "TEXT", + maxLength: 255, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 255, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 32) + .OldAnnotation("Relational:ColumnOrder", 30); + + migrationBuilder.AddColumn( + name: "AcoustId", + table: "Tracks", + type: "TEXT", + maxLength: 64, + nullable: true) + .Annotation("Relational:ColumnOrder", 44); + + migrationBuilder.AddColumn( + name: "Disambiguation", + table: "Tracks", + type: "TEXT", + maxLength: 255, + nullable: true) + .Annotation("Relational:ColumnOrder", 7); + + migrationBuilder.AddColumn( + name: "IsVideo", + table: "Tracks", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 31); + + migrationBuilder.AddColumn( + name: "LastMetadataUpdateUtc", + table: "Tracks", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 42); + + migrationBuilder.AddColumn( + name: "MetadataProvider", + table: "Tracks", + type: "TEXT", + maxLength: 100, + nullable: true) + .Annotation("Relational:ColumnOrder", 43); + + migrationBuilder.AddColumn( + name: "MetadataStatus", + table: "Tracks", + type: "TEXT", + maxLength: 20, + nullable: false, + defaultValue: "Pending") + .Annotation("Relational:ColumnOrder", 41); + + migrationBuilder.AddColumn( + name: "ReplayGainAlbumGain", + table: "Tracks", + type: "decimal(8,2)", + nullable: true) + .Annotation("Relational:ColumnOrder", 47); + + migrationBuilder.AddColumn( + name: "ReplayGainAlbumPeak", + table: "Tracks", + type: "decimal(8,6)", + nullable: true) + .Annotation("Relational:ColumnOrder", 48); + + migrationBuilder.AddColumn( + name: "ReplayGainTrackGain", + table: "Tracks", + type: "decimal(8,2)", + nullable: true) + .Annotation("Relational:ColumnOrder", 45); + + migrationBuilder.AddColumn( + name: "ReplayGainTrackPeak", + table: "Tracks", + type: "decimal(8,6)", + nullable: true) + .Annotation("Relational:ColumnOrder", 46); + + migrationBuilder.AddColumn( + name: "WorkType", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true) + .Annotation("Relational:ColumnOrder", 33); + + migrationBuilder.AlterColumn( + name: "Website", + table: "Artists", + type: "TEXT", + maxLength: 2048, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 2048, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 11) + .OldAnnotation("Relational:ColumnOrder", 3); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Artists", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 15) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Artists", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 16) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "MusicBrainzArtistId", + table: "Artists", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 4); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Artists", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 13) + .OldAnnotation("Relational:ColumnOrder", 5); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Artists", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 14) + .OldAnnotation("Relational:ColumnOrder", 6); + + migrationBuilder.AddColumn( + name: "Area", + table: "Artists", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "BeginArea", + table: "Artists", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "Country", + table: "Artists", + type: "TEXT", + maxLength: 2, + nullable: true) + .Annotation("Relational:ColumnOrder", 7); + + migrationBuilder.AddColumn( + name: "Disambiguation", + table: "Artists", + type: "TEXT", + maxLength: 255, + nullable: true) + .Annotation("Relational:ColumnOrder", 4); + + migrationBuilder.AddColumn( + name: "EndArea", + table: "Artists", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "Gender", + table: "Artists", + type: "TEXT", + maxLength: 20, + nullable: true) + .Annotation("Relational:ColumnOrder", 6); + + migrationBuilder.AddColumn( + name: "IsEnded", + table: "Artists", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 10); + + migrationBuilder.AddColumn( + name: "LastMetadataUpdateUtc", + table: "Artists", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 18); + + migrationBuilder.AddColumn( + name: "LifeSpanBegin", + table: "Artists", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 8); + + migrationBuilder.AddColumn( + name: "LifeSpanEnd", + table: "Artists", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 9); + + migrationBuilder.AddColumn( + name: "MetadataProvider", + table: "Artists", + type: "TEXT", + maxLength: 100, + nullable: true) + .Annotation("Relational:ColumnOrder", 19); + + migrationBuilder.AddColumn( + name: "MetadataStatus", + table: "Artists", + type: "TEXT", + maxLength: 20, + nullable: false, + defaultValue: "Pending") + .Annotation("Relational:ColumnOrder", 17); + + migrationBuilder.AddColumn( + name: "SortName", + table: "Artists", + type: "TEXT", + maxLength: 255, + nullable: true) + .Annotation("Relational:ColumnOrder", 3); + + migrationBuilder.AddColumn( + name: "Type", + table: "Artists", + type: "TEXT", + maxLength: 20, + nullable: true) + .Annotation("Relational:ColumnOrder", 5); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 34) + .OldAnnotation("Relational:ColumnOrder", 30); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 35) + .OldAnnotation("Relational:ColumnOrder", 31); + + migrationBuilder.AlterColumn( + name: "TotalTracks", + table: "Albums", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 22) + .OldAnnotation("Relational:ColumnOrder", 21); + + migrationBuilder.AlterColumn( + name: "TotalDiscs", + table: "Albums", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 21) + .OldAnnotation("Relational:ColumnOrder", 20); + + migrationBuilder.AlterColumn( + name: "ReleaseVersion", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "ReleaseStatus", + table: "Albums", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 20) + .OldAnnotation("Relational:ColumnOrder", 19); + + migrationBuilder.AlterColumn( + name: "ReleaseCountry", + table: "Albums", + type: "TEXT", + maxLength: 2, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 2, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 11) + .OldAnnotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "ReReleaseYear", + table: "Albums", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 10) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "ReReleaseDate", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateOnly), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "OriginalReleaseYear", + table: "Albums", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AlterColumn( + name: "OriginalReleaseDate", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateOnly), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 6); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageNativeName", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 18) + .OldAnnotation("Relational:ColumnOrder", 17); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageName", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 17) + .OldAnnotation("Relational:ColumnOrder", 16); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageCode", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 16) + .OldAnnotation("Relational:ColumnOrder", 15); + + migrationBuilder.AlterColumn( + name: "MusicBrainzReleaseId", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 29) + .OldAnnotation("Relational:ColumnOrder", 25); + + migrationBuilder.AlterColumn( + name: "MusicBrainzReleaseGroupId", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 30) + .OldAnnotation("Relational:ColumnOrder", 26); + + migrationBuilder.AlterColumn( + name: "MusicBrainzReleaseArtistId", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 31) + .OldAnnotation("Relational:ColumnOrder", 27); + + migrationBuilder.AlterColumn( + name: "MediaFormat", + table: "Albums", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 23) + .OldAnnotation("Relational:ColumnOrder", 22); + + migrationBuilder.AlterColumn( + name: "LanguageNativeName", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 15) + .OldAnnotation("Relational:ColumnOrder", 14); + + migrationBuilder.AlterColumn( + name: "LanguageName", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 14) + .OldAnnotation("Relational:ColumnOrder", 13); + + migrationBuilder.AlterColumn( + name: "LanguageCode", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 13) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Albums", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 32) + .OldAnnotation("Relational:ColumnOrder", 28); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Albums", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 33) + .OldAnnotation("Relational:ColumnOrder", 29); + + migrationBuilder.AlterColumn( + name: "Barcode", + table: "Albums", + type: "TEXT", + maxLength: 13, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 13, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 25) + .OldAnnotation("Relational:ColumnOrder", 23); + + migrationBuilder.AlterColumn( + name: "Script", + table: "Albums", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 19) + .OldAnnotation("Relational:ColumnOrder", 18); + + migrationBuilder.AddColumn( + name: "ASIN", + table: "Albums", + type: "TEXT", + maxLength: 20, + nullable: true) + .Annotation("Relational:ColumnOrder", 28); + + migrationBuilder.AddColumn( + name: "Disambiguation", + table: "Albums", + type: "TEXT", + maxLength: 255, + nullable: true) + .Annotation("Relational:ColumnOrder", 6); + + migrationBuilder.AddColumn( + name: "Label", + table: "Albums", + type: "TEXT", + maxLength: 255, + nullable: true) + .Annotation("Relational:ColumnOrder", 27); + + migrationBuilder.AddColumn( + name: "LastMetadataUpdateUtc", + table: "Albums", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 37); + + migrationBuilder.AddColumn( + name: "MetadataProvider", + table: "Albums", + type: "TEXT", + maxLength: 100, + nullable: true) + .Annotation("Relational:ColumnOrder", 38); + + migrationBuilder.AddColumn( + name: "MetadataStatus", + table: "Albums", + type: "TEXT", + maxLength: 20, + nullable: false, + defaultValue: "Pending") + .Annotation("Relational:ColumnOrder", 36); + + migrationBuilder.AddColumn( + name: "ReleaseTitle", + table: "Albums", + type: "TEXT", + maxLength: 255, + nullable: true) + .Annotation("Relational:ColumnOrder", 26); + + migrationBuilder.CreateTable( + name: "AlbumCatalogNumbers", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + CatalogNumber = table.Column(type: "TEXT", maxLength: 50, nullable: false), + AlbumId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AlbumCatalogNumbers", x => x.Id); + table.ForeignKey( + name: "FK_AlbumCatalogNumbers_Albums_AlbumId", + column: x => x.AlbumId, + principalTable: "Albums", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AlbumReleaseTypes", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ReleaseType = table.Column(type: "TEXT", maxLength: 50, nullable: false), + AlbumId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AlbumReleaseTypes", x => x.Id); + table.ForeignKey( + name: "FK_AlbumReleaseTypes_Albums_AlbumId", + column: x => x.AlbumId, + principalTable: "Albums", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ArtistAliases", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 255, nullable: false), + SortName = table.Column(type: "TEXT", maxLength: 255, nullable: true), + Type = table.Column(type: "TEXT", maxLength: 50, nullable: true), + Locale = table.Column(type: "TEXT", maxLength: 20, nullable: true), + IsPrimary = table.Column(type: "INTEGER", nullable: false), + BeginDate = table.Column(type: "TEXT", nullable: true), + EndDate = table.Column(type: "TEXT", nullable: true), + IsEnded = table.Column(type: "INTEGER", nullable: false), + ArtistId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtistAliases", x => x.Id); + table.ForeignKey( + name: "FK_ArtistAliases_Artists_ArtistId", + column: x => x.ArtistId, + principalTable: "Artists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ArtistGenres", + columns: table => new + { + ArtistId = table.Column(type: "TEXT", nullable: false), + GenreId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtistGenres", x => new { x.ArtistId, x.GenreId }); + table.ForeignKey( + name: "FK_ArtistGenres_Artists_ArtistId", + column: x => x.ArtistId, + principalTable: "Artists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ArtistGenres_Genres_GenreId", + column: x => x.GenreId, + principalTable: "Genres", + principalColumn: "Name", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ArtistIpis", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Value = table.Column(type: "TEXT", maxLength: 20, nullable: false), + ArtistId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtistIpis", x => x.Id); + table.ForeignKey( + name: "FK_ArtistIpis_Artists_ArtistId", + column: x => x.ArtistId, + principalTable: "Artists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ArtistIsnis", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Value = table.Column(type: "TEXT", maxLength: 20, nullable: false), + ArtistId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtistIsnis", x => x.Id); + table.ForeignKey( + name: "FK_ArtistIsnis_Artists_ArtistId", + column: x => x.ArtistId, + principalTable: "Artists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ArtistRatings", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Source = table.Column(type: "TEXT", maxLength: 50, nullable: true), + ArtistId = table.Column(type: "TEXT", nullable: false), + Value = table.Column(type: "decimal(3,2)", nullable: false), + MaxValue = table.Column(type: "decimal(3,2)", nullable: false), + VoteCount = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtistRatings", x => x.Id); + table.ForeignKey( + name: "FK_ArtistRatings_Artists_ArtistId", + column: x => x.ArtistId, + principalTable: "Artists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ArtistTags", + columns: table => new + { + ArtistId = table.Column(type: "TEXT", nullable: false), + TagId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtistTags", x => new { x.ArtistId, x.TagId }); + table.ForeignKey( + name: "FK_ArtistTags_Artists_ArtistId", + column: x => x.ArtistId, + principalTable: "Artists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ArtistTags_Tags_TagId", + column: x => x.TagId, + principalTable: "Tags", + principalColumn: "Name", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "MusicArtwork", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + OwnerType = table.Column(type: "TEXT", maxLength: 50, nullable: false), + OwnerId = table.Column(type: "TEXT", nullable: false), + ArtworkType = table.Column(type: "TEXT", maxLength: 50, nullable: false), + Ordinal = table.Column(type: "INTEGER", nullable: false), + FileName = table.Column(type: "TEXT", maxLength: 2048, nullable: true), + ContentHash = table.Column(type: "INTEGER", nullable: false), + Status = table.Column(type: "TEXT", maxLength: 20, nullable: false), + Provider = table.Column(type: "TEXT", maxLength: 100, nullable: true), + LastUpdateUtc = table.Column(type: "TEXT", nullable: true), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_MusicArtwork", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "MusicLibraryScanItemMetadata", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + LibraryScanId = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + Path = table.Column(type: "TEXT", maxLength: 2048, nullable: false), + ArtistName = table.Column(type: "TEXT", maxLength: 255, nullable: true), + ReleaseType = table.Column(type: "TEXT", maxLength: 50, nullable: true), + ReleaseYear = table.Column(type: "INTEGER", nullable: true), + ReleaseName = table.Column(type: "TEXT", maxLength: 255, nullable: true), + TrackTitle = table.Column(type: "TEXT", maxLength: 255, nullable: true), + TrackNumber = table.Column(type: "INTEGER", nullable: true), + DiscNumber = table.Column(type: "INTEGER", nullable: true), + DurationInSeconds = table.Column(type: "INTEGER", nullable: false), + SampleRate = table.Column(type: "INTEGER", nullable: false), + Channels = table.Column(type: "INTEGER", nullable: false), + BitDepth = table.Column(type: "INTEGER", nullable: true), + AudioCodec = table.Column(type: "TEXT", maxLength: 50, nullable: true), + Bitrate = table.Column(type: "INTEGER", nullable: true), + MusicBrainzArtistId = table.Column(type: "TEXT", nullable: true), + MusicBrainzReleaseArtistId = table.Column(type: "TEXT", nullable: true), + MusicBrainzReleaseGroupId = table.Column(type: "TEXT", nullable: true), + MusicBrainzReleaseId = table.Column(type: "TEXT", nullable: true), + MusicBrainzRecordingId = table.Column(type: "TEXT", nullable: true), + MusicBrainzTrackId = table.Column(type: "TEXT", nullable: true), + MusicBrainzWorkId = table.Column(type: "TEXT", nullable: true), + WorkTitle = table.Column(type: "TEXT", maxLength: 255, nullable: true), + AcoustId = table.Column(type: "TEXT", maxLength: 64, nullable: true), + ReplayGainTrackGain = table.Column(type: "decimal(8,2)", nullable: true), + ReplayGainTrackPeak = table.Column(type: "decimal(8,6)", nullable: true), + ReplayGainAlbumGain = table.Column(type: "decimal(8,2)", nullable: true), + ReplayGainAlbumPeak = table.Column(type: "decimal(8,6)", nullable: true), + Moods = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MusicLibraryScanItemMetadata", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "TrackWorkIswcs", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Value = table.Column(type: "TEXT", maxLength: 20, nullable: false), + TrackId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TrackWorkIswcs", x => x.Id); + table.ForeignKey( + name: "FK_TrackWorkIswcs_Tracks_TrackId", + column: x => x.TrackId, + principalTable: "Tracks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TrackWorkLanguages", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + LanguageCode = table.Column(type: "TEXT", maxLength: 5, nullable: false), + LanguageName = table.Column(type: "TEXT", maxLength: 100, nullable: false), + NativeName = table.Column(type: "TEXT", maxLength: 100, nullable: true), + TrackId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TrackWorkLanguages", x => x.Id); + table.ForeignKey( + name: "FK_TrackWorkLanguages_Tracks_TrackId", + column: x => x.TrackId, + principalTable: "Tracks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AlbumCatalogNumbers_AlbumId", + table: "AlbumCatalogNumbers", + column: "AlbumId"); + + migrationBuilder.CreateIndex( + name: "IX_AlbumReleaseTypes_AlbumId", + table: "AlbumReleaseTypes", + column: "AlbumId"); + + migrationBuilder.CreateIndex( + name: "IX_ArtistAliases_ArtistId", + table: "ArtistAliases", + column: "ArtistId"); + + migrationBuilder.CreateIndex( + name: "IX_ArtistGenres_GenreId", + table: "ArtistGenres", + column: "GenreId"); + + migrationBuilder.CreateIndex( + name: "IX_ArtistIpis_ArtistId", + table: "ArtistIpis", + column: "ArtistId"); + + migrationBuilder.CreateIndex( + name: "IX_ArtistIsnis_ArtistId", + table: "ArtistIsnis", + column: "ArtistId"); + + migrationBuilder.CreateIndex( + name: "IX_ArtistRatings_ArtistId", + table: "ArtistRatings", + column: "ArtistId"); + + migrationBuilder.CreateIndex( + name: "IX_ArtistTags_TagId", + table: "ArtistTags", + column: "TagId"); + + migrationBuilder.CreateIndex( + name: "IX_MusicArtwork_OwnerType_OwnerId_ArtworkType_Ordinal", + table: "MusicArtwork", + columns: new[] { "OwnerType", "OwnerId", "ArtworkType", "Ordinal" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MusicArtwork_Status", + table: "MusicArtwork", + column: "Status"); + + migrationBuilder.CreateIndex( + name: "IX_MusicLibraryScanItemMetadata_LibraryScanId_Path", + table: "MusicLibraryScanItemMetadata", + columns: new[] { "LibraryScanId", "Path" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_TrackWorkIswcs_TrackId", + table: "TrackWorkIswcs", + column: "TrackId"); + + migrationBuilder.CreateIndex( + name: "IX_TrackWorkLanguages_TrackId", + table: "TrackWorkLanguages", + column: "TrackId"); + + migrationBuilder.AddColumn( + name: "ShouldAggregateArtworkWhenMissing", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 13); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ShouldAggregateArtworkWhenMissing", + table: "UserSettings"); + + migrationBuilder.DropTable( + name: "AlbumCatalogNumbers"); + + migrationBuilder.DropTable( + name: "AlbumReleaseTypes"); + + migrationBuilder.DropTable( + name: "ArtistAliases"); + + migrationBuilder.DropTable( + name: "ArtistGenres"); + + migrationBuilder.DropTable( + name: "ArtistIpis"); + + migrationBuilder.DropTable( + name: "ArtistIsnis"); + + migrationBuilder.DropTable( + name: "ArtistRatings"); + + migrationBuilder.DropTable( + name: "ArtistTags"); + + migrationBuilder.DropTable( + name: "MusicArtwork"); + + migrationBuilder.DropTable( + name: "MusicLibraryScanItemMetadata"); + + migrationBuilder.DropTable( + name: "TrackWorkIswcs"); + + migrationBuilder.DropTable( + name: "TrackWorkLanguages"); + + migrationBuilder.DropColumn( + name: "AcoustId", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "Disambiguation", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "IsVideo", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "LastMetadataUpdateUtc", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "MetadataProvider", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "MetadataStatus", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "ReplayGainAlbumGain", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "ReplayGainAlbumPeak", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "ReplayGainTrackGain", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "ReplayGainTrackPeak", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "WorkType", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "Area", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "BeginArea", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "Country", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "Disambiguation", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "EndArea", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "Gender", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "IsEnded", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "LastMetadataUpdateUtc", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "LifeSpanBegin", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "LifeSpanEnd", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "MetadataProvider", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "MetadataStatus", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "SortName", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "Type", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "ASIN", + table: "Albums"); + + migrationBuilder.DropColumn( + name: "Disambiguation", + table: "Albums"); + + migrationBuilder.DropColumn( + name: "Label", + table: "Albums"); + + migrationBuilder.DropColumn( + name: "LastMetadataUpdateUtc", + table: "Albums"); + + migrationBuilder.DropColumn( + name: "MetadataProvider", + table: "Albums"); + + migrationBuilder.DropColumn( + name: "MetadataStatus", + table: "Albums"); + + migrationBuilder.DropColumn( + name: "ReleaseTitle", + table: "Albums"); + + migrationBuilder.RenameColumn( + name: "WorkTitle", + table: "Tracks", + newName: "Work"); + + migrationBuilder.RenameColumn( + name: "Script", + table: "Albums", + newName: "ReleaseType"); + + migrationBuilder.RenameColumn( + name: "Packaging", + table: "Albums", + newName: "CatalogNumber"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 36) + .OldAnnotation("Relational:ColumnOrder", 39); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 37) + .OldAnnotation("Relational:ColumnOrder", 40); + + migrationBuilder.AlterColumn( + name: "TrackNumber", + table: "Tracks", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 25) + .OldAnnotation("Relational:ColumnOrder", 26); + + migrationBuilder.AlterColumn( + name: "Script", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 27) + .OldAnnotation("Relational:ColumnOrder", 28); + + migrationBuilder.AlterColumn( + name: "SampleRate", + table: "Tracks", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 20) + .OldAnnotation("Relational:ColumnOrder", 21); + + migrationBuilder.AlterColumn( + name: "ReleaseVersion", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 13); + + migrationBuilder.AlterColumn( + name: "ReleaseCountry", + table: "Tracks", + type: "TEXT", + maxLength: 2, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 2, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 11) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AlterColumn( + name: "ReReleaseYear", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 10) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "ReReleaseDate", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateOnly), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "OriginalReleaseYear", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "OriginalReleaseDate", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateOnly), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageNativeName", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 18) + .OldAnnotation("Relational:ColumnOrder", 19); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageName", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 17) + .OldAnnotation("Relational:ColumnOrder", 18); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageCode", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 16) + .OldAnnotation("Relational:ColumnOrder", 17); + + migrationBuilder.AlterColumn( + name: "MusicBrainzWorkId", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 33) + .OldAnnotation("Relational:ColumnOrder", 36); + + migrationBuilder.AlterColumn( + name: "MusicBrainzTrackId", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 32) + .OldAnnotation("Relational:ColumnOrder", 35); + + migrationBuilder.AlterColumn( + name: "MusicBrainzRecordingId", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 31) + .OldAnnotation("Relational:ColumnOrder", 34); + + migrationBuilder.AlterColumn( + name: "LanguageNativeName", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 15) + .OldAnnotation("Relational:ColumnOrder", 16); + + migrationBuilder.AlterColumn( + name: "LanguageName", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 14) + .OldAnnotation("Relational:ColumnOrder", 15); + + migrationBuilder.AlterColumn( + name: "LanguageCode", + table: "Tracks", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 13) + .OldAnnotation("Relational:ColumnOrder", 14); + + migrationBuilder.AlterColumn( + name: "Key", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 28) + .OldAnnotation("Relational:ColumnOrder", 29); + + migrationBuilder.AlterColumn( + name: "DurationInSeconds", + table: "Tracks", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 19) + .OldAnnotation("Relational:ColumnOrder", 20); + + migrationBuilder.AlterColumn( + name: "DiscNumber", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 26) + .OldAnnotation("Relational:ColumnOrder", 27); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Tracks", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 34) + .OldAnnotation("Relational:ColumnOrder", 37); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Tracks", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 35) + .OldAnnotation("Relational:ColumnOrder", 38); + + migrationBuilder.AlterColumn( + name: "Channels", + table: "Tracks", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 21) + .OldAnnotation("Relational:ColumnOrder", 22); + + migrationBuilder.AlterColumn( + name: "Bpm", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 29) + .OldAnnotation("Relational:ColumnOrder", 30); + + migrationBuilder.AlterColumn( + name: "Bitrate", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 24) + .OldAnnotation("Relational:ColumnOrder", 25); + + migrationBuilder.AlterColumn( + name: "BitDepth", + table: "Tracks", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 22) + .OldAnnotation("Relational:ColumnOrder", 23); + + migrationBuilder.AlterColumn( + name: "AudioCodec", + table: "Tracks", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 23) + .OldAnnotation("Relational:ColumnOrder", 24); + + migrationBuilder.AlterColumn( + name: "Work", + table: "Tracks", + type: "TEXT", + maxLength: 255, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 255, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 30) + .OldAnnotation("Relational:ColumnOrder", 32); + + migrationBuilder.AlterColumn( + name: "Website", + table: "Artists", + type: "TEXT", + maxLength: 2048, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 2048, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 3) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Artists", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 15); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Artists", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 16); + + migrationBuilder.AlterColumn( + name: "MusicBrainzArtistId", + table: "Artists", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 4) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Artists", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 5) + .OldAnnotation("Relational:ColumnOrder", 13); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Artists", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 6) + .OldAnnotation("Relational:ColumnOrder", 14); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 30) + .OldAnnotation("Relational:ColumnOrder", 34); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 31) + .OldAnnotation("Relational:ColumnOrder", 35); + + migrationBuilder.AlterColumn( + name: "TotalTracks", + table: "Albums", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .Annotation("Relational:ColumnOrder", 21) + .OldAnnotation("Relational:ColumnOrder", 22); + + migrationBuilder.AlterColumn( + name: "TotalDiscs", + table: "Albums", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 20) + .OldAnnotation("Relational:ColumnOrder", 21); + + migrationBuilder.AlterColumn( + name: "ReleaseVersion", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 11) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AlterColumn( + name: "ReleaseStatus", + table: "Albums", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 19) + .OldAnnotation("Relational:ColumnOrder", 20); + + migrationBuilder.AlterColumn( + name: "ReleaseCountry", + table: "Albums", + type: "TEXT", + maxLength: 2, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 2, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 10) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "ReReleaseYear", + table: "Albums", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "ReReleaseDate", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateOnly), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "OriginalReleaseYear", + table: "Albums", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "OriginalReleaseDate", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateOnly), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 6) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageNativeName", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 17) + .OldAnnotation("Relational:ColumnOrder", 18); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageName", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 16) + .OldAnnotation("Relational:ColumnOrder", 17); + + migrationBuilder.AlterColumn( + name: "OriginalLanguageCode", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 15) + .OldAnnotation("Relational:ColumnOrder", 16); + + migrationBuilder.AlterColumn( + name: "MusicBrainzReleaseId", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 25) + .OldAnnotation("Relational:ColumnOrder", 29); + + migrationBuilder.AlterColumn( + name: "MusicBrainzReleaseGroupId", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 26) + .OldAnnotation("Relational:ColumnOrder", 30); + + migrationBuilder.AlterColumn( + name: "MusicBrainzReleaseArtistId", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 27) + .OldAnnotation("Relational:ColumnOrder", 31); + + migrationBuilder.AlterColumn( + name: "MediaFormat", + table: "Albums", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 22) + .OldAnnotation("Relational:ColumnOrder", 23); + + migrationBuilder.AlterColumn( + name: "LanguageNativeName", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 14) + .OldAnnotation("Relational:ColumnOrder", 15); + + migrationBuilder.AlterColumn( + name: "LanguageName", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 13) + .OldAnnotation("Relational:ColumnOrder", 14); + + migrationBuilder.AlterColumn( + name: "LanguageCode", + table: "Albums", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 13); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Albums", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 28) + .OldAnnotation("Relational:ColumnOrder", 32); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Albums", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 29) + .OldAnnotation("Relational:ColumnOrder", 33); + + migrationBuilder.AlterColumn( + name: "Barcode", + table: "Albums", + type: "TEXT", + maxLength: 13, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 13, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 23) + .OldAnnotation("Relational:ColumnOrder", 25); + + migrationBuilder.AlterColumn( + name: "ReleaseType", + table: "Albums", + type: "TEXT", + maxLength: 50, + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50, + oldNullable: true) + .Annotation("Relational:ColumnOrder", 18) + .OldAnnotation("Relational:ColumnOrder", 19); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261008064333_AddsLibraryPathTemplate.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261008064333_AddsLibraryPathTemplate.Designer.cs new file mode 100644 index 00000000..412d7c15 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261008064333_AddsLibraryPathTemplate.Designer.cs @@ -0,0 +1,3425 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261008064333_AddsLibraryPathTemplate")] + partial class AddsLibraryPathTemplate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261008064333_AddsLibraryPathTemplate.cs b/src/Lumina.DataAccess/Common/Migrations/20261008064333_AddsLibraryPathTemplate.cs new file mode 100644 index 00000000..6378425a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261008064333_AddsLibraryPathTemplate.cs @@ -0,0 +1,146 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsLibraryPathTemplate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 14) + .OldAnnotation("Relational:ColumnOrder", 13); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 15) + .OldAnnotation("Relational:ColumnOrder", 14); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 13) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AddColumn( + name: "PathTemplateFingerprint", + table: "Libraries", + type: "TEXT", + maxLength: 64, + nullable: true) + .Annotation("Relational:ColumnOrder", 11); + + migrationBuilder.CreateTable( + name: "LibraryPathTemplateParts", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Position = table.Column(type: "INTEGER", nullable: false), + Kind = table.Column(type: "TEXT", maxLength: 32, nullable: false), + Representation = table.Column(type: "TEXT", maxLength: 512, nullable: false), + IsOptional = table.Column(type: "INTEGER", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LibraryPathTemplateParts", x => x.Id); + table.ForeignKey( + name: "FK_LibraryPathTemplateParts_Libraries_LibraryId", + column: x => x.LibraryId, + principalTable: "Libraries", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_LibraryPathTemplateParts_LibraryId_Position", + table: "LibraryPathTemplateParts", + columns: new[] { "LibraryId", "Position" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "LibraryPathTemplateParts"); + + migrationBuilder.DropColumn( + name: "PathTemplateFingerprint", + table: "Libraries"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 13) + .OldAnnotation("Relational:ColumnOrder", 14); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 14) + .OldAnnotation("Relational:ColumnOrder", 15); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 11) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 13); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 0d628bfb..d2db1993 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -47,6 +47,36 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("AlbumTags", (string)null); }); + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + modelBuilder.Entity("BookGenres", b => { b.Property("BookId") @@ -376,6 +406,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(0); + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + b.Property("ArtistId") .HasColumnType("TEXT") .HasColumnOrder(1); @@ -383,38 +418,47 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("Barcode") .HasMaxLength(13) .HasColumnType("TEXT") - .HasColumnOrder(23); - - b.Property("CatalogNumber") - .HasMaxLength(50) - .HasColumnType("TEXT") - .HasColumnOrder(24); + .HasColumnOrder(25); b.Property("CreatedBy") .HasColumnType("TEXT") - .HasColumnOrder(29); + .HasColumnOrder(33); b.Property("CreatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(28); + .HasColumnOrder(32); b.Property("Description") .HasMaxLength(2000) .HasColumnType("TEXT") .HasColumnOrder(5); - b.Property("LanguageCode") + b.Property("Disambiguation") + .HasMaxLength(255) .HasColumnType("TEXT") - .HasColumnOrder(12); + .HasColumnOrder(6); - b.Property("LanguageName") + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") .HasColumnType("TEXT") .HasColumnOrder(13); - b.Property("LanguageNativeName") + b.Property("LanguageName") .HasColumnType("TEXT") .HasColumnOrder(14); + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + b.Property("LibraryId") .HasColumnType("TEXT") .HasColumnOrder(2); @@ -422,71 +466,94 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("MediaFormat") .HasMaxLength(50) .HasColumnType("TEXT") - .HasColumnOrder(22); + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); b.Property("MusicBrainzReleaseArtistId") .HasColumnType("TEXT") - .HasColumnOrder(27); + .HasColumnOrder(31); b.Property("MusicBrainzReleaseGroupId") .HasColumnType("TEXT") - .HasColumnOrder(26); + .HasColumnOrder(30); b.Property("MusicBrainzReleaseId") .HasColumnType("TEXT") - .HasColumnOrder(25); + .HasColumnOrder(29); b.Property("OriginalLanguageCode") .HasColumnType("TEXT") - .HasColumnOrder(15); + .HasColumnOrder(16); b.Property("OriginalLanguageName") .HasColumnType("TEXT") - .HasColumnOrder(16); + .HasColumnOrder(17); b.Property("OriginalLanguageNativeName") .HasColumnType("TEXT") - .HasColumnOrder(17); + .HasColumnOrder(18); b.Property("OriginalReleaseDate") .HasColumnType("TEXT") - .HasColumnOrder(6); + .HasColumnOrder(7); b.Property("OriginalReleaseYear") .HasColumnType("INTEGER") - .HasColumnOrder(7); + .HasColumnOrder(8); b.Property("OriginalTitle") .HasMaxLength(255) .HasColumnType("TEXT") .HasColumnOrder(4); + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + b.Property("ReReleaseDate") .HasColumnType("TEXT") - .HasColumnOrder(8); + .HasColumnOrder(9); b.Property("ReReleaseYear") .HasColumnType("INTEGER") - .HasColumnOrder(9); + .HasColumnOrder(10); b.Property("ReleaseCountry") .HasMaxLength(2) .HasColumnType("TEXT") - .HasColumnOrder(10); + .HasColumnOrder(11); b.Property("ReleaseStatus") .HasMaxLength(50) .HasColumnType("TEXT") - .HasColumnOrder(19); + .HasColumnOrder(20); - b.Property("ReleaseType") - .HasMaxLength(50) + b.Property("ReleaseTitle") + .HasMaxLength(255) .HasColumnType("TEXT") - .HasColumnOrder(18); + .HasColumnOrder(26); b.Property("ReleaseVersion") .HasColumnType("TEXT") - .HasColumnOrder(11); + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); b.Property("Title") .IsRequired() @@ -496,19 +563,19 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("TotalDiscs") .HasColumnType("INTEGER") - .HasColumnOrder(20); + .HasColumnOrder(21); b.Property("TotalTracks") .HasColumnType("INTEGER") - .HasColumnOrder(21); + .HasColumnOrder(22); b.Property("UpdatedBy") .HasColumnType("TEXT") - .HasColumnOrder(31); + .HasColumnOrder(35); b.Property("UpdatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(30); + .HasColumnOrder(34); b.HasKey("Id"); @@ -571,21 +638,65 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(0); + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + b.Property("CreatedBy") .HasColumnType("TEXT") - .HasColumnOrder(6); + .HasColumnOrder(14); b.Property("CreatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(5); + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); b.Property("LibraryId") .HasColumnType("TEXT") .HasColumnOrder(1); + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + b.Property("MusicBrainzArtistId") .HasColumnType("TEXT") - .HasColumnOrder(4); + .HasColumnOrder(12); b.Property("Name") .IsRequired() @@ -593,18 +704,28 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(2); + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + b.Property("UpdatedBy") .HasColumnType("TEXT") - .HasColumnOrder(8); + .HasColumnOrder(16); b.Property("UpdatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(7); + .HasColumnOrder(15); b.Property("Website") .HasMaxLength(2048) .HasColumnType("TEXT") - .HasColumnOrder(3); + .HasColumnOrder(11); b.HasKey("Id"); @@ -614,6 +735,226 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Artists", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => { b.Property("Id") @@ -666,6 +1007,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(0); + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + b.Property("AlbumId") .HasColumnType("TEXT") .HasColumnOrder(1); @@ -673,97 +1019,123 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("AudioCodec") .HasMaxLength(50) .HasColumnType("TEXT") - .HasColumnOrder(23); + .HasColumnOrder(24); b.Property("BitDepth") .HasColumnType("INTEGER") - .HasColumnOrder(22); + .HasColumnOrder(23); b.Property("Bitrate") .HasColumnType("INTEGER") - .HasColumnOrder(24); + .HasColumnOrder(25); b.Property("Bpm") .HasColumnType("INTEGER") - .HasColumnOrder(29); + .HasColumnOrder(30); b.Property("Channels") .HasColumnType("INTEGER") - .HasColumnOrder(21); + .HasColumnOrder(22); b.Property("CreatedBy") .HasColumnType("TEXT") - .HasColumnOrder(35); + .HasColumnOrder(38); b.Property("CreatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(34); + .HasColumnOrder(37); b.Property("Description") .HasMaxLength(2000) .HasColumnType("TEXT") .HasColumnOrder(6); + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + b.Property("DiscNumber") .HasColumnType("INTEGER") - .HasColumnOrder(26); + .HasColumnOrder(27); b.Property("DurationInSeconds") .HasColumnType("INTEGER") - .HasColumnOrder(19); + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); b.Property("Key") .HasMaxLength(50) .HasColumnType("TEXT") - .HasColumnOrder(28); + .HasColumnOrder(29); b.Property("LanguageCode") .HasColumnType("TEXT") - .HasColumnOrder(13); + .HasColumnOrder(14); b.Property("LanguageName") .HasColumnType("TEXT") - .HasColumnOrder(14); + .HasColumnOrder(15); b.Property("LanguageNativeName") .HasColumnType("TEXT") - .HasColumnOrder(15); + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); b.Property("LibraryId") .HasColumnType("TEXT") .HasColumnOrder(2); + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + b.Property("MusicBrainzRecordingId") .HasColumnType("TEXT") - .HasColumnOrder(31); + .HasColumnOrder(34); b.Property("MusicBrainzTrackId") .HasColumnType("TEXT") - .HasColumnOrder(32); + .HasColumnOrder(35); b.Property("MusicBrainzWorkId") .HasColumnType("TEXT") - .HasColumnOrder(33); + .HasColumnOrder(36); b.Property("OriginalLanguageCode") .HasColumnType("TEXT") - .HasColumnOrder(16); + .HasColumnOrder(17); b.Property("OriginalLanguageName") .HasColumnType("TEXT") - .HasColumnOrder(17); + .HasColumnOrder(18); b.Property("OriginalLanguageNativeName") .HasColumnType("TEXT") - .HasColumnOrder(18); + .HasColumnOrder(19); b.Property("OriginalReleaseDate") .HasColumnType("TEXT") - .HasColumnOrder(7); + .HasColumnOrder(8); b.Property("OriginalReleaseYear") .HasColumnType("INTEGER") - .HasColumnOrder(8); + .HasColumnOrder(9); b.Property("OriginalTitle") .HasMaxLength(255) @@ -778,29 +1150,45 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("ReReleaseDate") .HasColumnType("TEXT") - .HasColumnOrder(9); + .HasColumnOrder(10); b.Property("ReReleaseYear") .HasColumnType("INTEGER") - .HasColumnOrder(10); + .HasColumnOrder(11); b.Property("ReleaseCountry") .HasMaxLength(2) .HasColumnType("TEXT") - .HasColumnOrder(11); + .HasColumnOrder(12); b.Property("ReleaseVersion") .HasColumnType("TEXT") - .HasColumnOrder(12); + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); b.Property("SampleRate") .HasColumnType("INTEGER") - .HasColumnOrder(20); + .HasColumnOrder(21); b.Property("Script") .HasMaxLength(50) .HasColumnType("TEXT") - .HasColumnOrder(27); + .HasColumnOrder(28); b.Property("Title") .IsRequired() @@ -810,20 +1198,25 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("TrackNumber") .HasColumnType("INTEGER") - .HasColumnOrder(25); + .HasColumnOrder(26); b.Property("UpdatedBy") .HasColumnType("TEXT") - .HasColumnOrder(37); + .HasColumnOrder(40); b.Property("UpdatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(36); + .HasColumnOrder(39); - b.Property("Work") + b.Property("WorkTitle") .HasMaxLength(255) .HasColumnType("TEXT") - .HasColumnOrder(30); + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); b.HasKey("Id"); @@ -884,11 +1277,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("CreatedBy") .HasColumnType("TEXT") - .HasColumnOrder(12); + .HasColumnOrder(13); b.Property("CreatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(11); + .HasColumnOrder(12); b.Property("IsEnabled") .ValueGeneratedOnAdd() @@ -910,6 +1303,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(9); + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + b.Property("ShouldSaveMetadataInMediaDirectories") .HasColumnType("INTEGER") .HasColumnOrder(7); @@ -926,11 +1324,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("UpdatedBy") .HasColumnType("TEXT") - .HasColumnOrder(14); + .HasColumnOrder(15); b.Property("UpdatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(13); + .HasColumnOrder(14); b.Property("UserId") .HasColumnType("TEXT"); @@ -1963,6 +2361,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(3); + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + b.Property("ShouldAggregateMetadataWhenMissing") .HasColumnType("INTEGER") .HasColumnOrder(10); @@ -2059,6 +2461,36 @@ namespace Lumina.DataAccess.Common.Migrations .IsRequired(); }); + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("BookGenres", b => { b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) @@ -2163,6 +2595,30 @@ namespace Lumina.DataAccess.Common.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => { b1.Property("Id") @@ -2195,9 +2651,37 @@ namespace Lumina.DataAccess.Common.Migrations .HasForeignKey("AlbumId"); }); + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + b.Navigation("Artist"); + b.Navigation("CatalogNumbers"); + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); }); modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => @@ -2209,6 +2693,238 @@ namespace Lumina.DataAccess.Common.Migrations .IsRequired(); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => { b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) @@ -2307,6 +3023,63 @@ namespace Lumina.DataAccess.Common.Migrations .HasForeignKey("TrackId"); }); + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + b.Navigation("Album"); b.Navigation("Isrcs"); @@ -2314,6 +3087,10 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("Moods"); b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); }); modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => @@ -2358,8 +3135,47 @@ namespace Lumina.DataAccess.Common.Migrations .HasForeignKey("LibraryId"); }); + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + b.Navigation("ContentLocations"); + b.Navigation("PathTemplateParts"); + b.Navigation("User"); }); diff --git a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index f0fca470..b1490003 100644 --- a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -308,6 +308,27 @@ internal sealed class BookRepository : IBookRepository .FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false); } + /// + /// Gets the subset of that is already used by a book of the library identified by . + /// + /// The Id of the library whose books are searched. + /// The book paths to check. + /// Cancellation token that can be used to stop the execution. + /// An containing either the paths that are already used, or an error. + public async Task>> GetExistingPathsAsync(Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken) + { + if (paths.Count == 0) + return Result.From>([]); + + // The stored paths are compared ordinally, matching the case sensitive comparison used by the unique index of the storage medium. + List distinctPaths = [.. paths.Distinct(StringComparer.Ordinal)]; + List existingPaths = await _luminaDbContext.Books + .Where(repositoryBook => repositoryBook.LibraryId == libraryId && distinctPaths.Contains(repositoryBook.Path)) + .Select(repositoryBook => repositoryBook.Path) + .ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From>(existingPaths); + } + /// /// Gets a page of the books of the media library identified by whose metadata has not been enriched yet, /// ordered by path, using keyset pagination. diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs index c5168a61..4ecc888d 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs @@ -64,6 +64,7 @@ internal sealed class LibraryRepository : ILibraryRepository if (shouldIncludeNavigationProperties) query = query .Include(library => library.ContentLocations) + .Include(library => library.PathTemplateParts) .AsSplitQuery(); return await query.FirstOrDefaultAsync(library => library.Id == id, cancellationToken).ConfigureAwait(false); } @@ -77,6 +78,7 @@ internal sealed class LibraryRepository : ILibraryRepository { return await _luminaDbContext.Libraries .Include(library => library.ContentLocations) + .Include(library => library.PathTemplateParts) .AsSplitQuery() .Where(library => library.IsEnabled) .ToListAsync(cancellationToken).ConfigureAwait(false); @@ -91,6 +93,7 @@ internal sealed class LibraryRepository : ILibraryRepository { return await _luminaDbContext.Libraries .Include(library => library.ContentLocations) + .Include(library => library.PathTemplateParts) .AsSplitQuery() .Where(library => library.IsEnabled && !library.IsLocked) .ToListAsync(cancellationToken).ConfigureAwait(false); @@ -116,6 +119,7 @@ internal sealed class LibraryRepository : ILibraryRepository if (shouldIncludeNavigationProperties) query = query .Include(library => library.ContentLocations) + .Include(library => library.PathTemplateParts) .AsSplitQuery(); // If no pagination was requested, return all the media libraries. @@ -161,6 +165,7 @@ internal sealed class LibraryRepository : ILibraryRepository { LibraryEntity? foundLibrary = await _luminaDbContext.Libraries .Include(library => library.ContentLocations) + .Include(library => library.PathTemplateParts) .AsSplitQuery() .FirstOrDefaultAsync(library => library.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundLibrary is null) @@ -179,6 +184,17 @@ internal sealed class LibraryRepository : ILibraryRepository shouldReplace: (existingContentLocation, incomingContentLocation) => false, createNew: incomingContentLocation => incomingContentLocation); + // A path template part is matched by its position in the template, and is replaced only when its editable values actually changed. + CollectionReconciler.Reconcile( + foundLibrary.PathTemplateParts, + data.PathTemplateParts, + existingPart => existingPart.Position, + incomingPart => incomingPart.Position, + shouldReplace: (existingPart, incomingPart) => existingPart.Kind != incomingPart.Kind + || existingPart.Representation != incomingPart.Representation + || existingPart.IsOptional != incomingPart.IsOptional, + createNew: incomingPart => incomingPart); + return Result.Updated; } @@ -192,6 +208,7 @@ internal sealed class LibraryRepository : ILibraryRepository { LibraryEntity? library = await _luminaDbContext.Libraries .Include(library => library.ContentLocations) + .Include(library => library.PathTemplateParts) .AsSplitQuery() .FirstOrDefaultAsync(library => library.Id == id, cancellationToken) .ConfigureAwait(false); diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs index 4c8a1c2a..d7719b69 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs @@ -114,4 +114,20 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundLibraryScan, data); return Result.Updated; } + + /// + /// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still + /// or , as failed. + /// + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> FailInterruptedScansAsync(CancellationToken cancellationToken) + { + // The scans that were pending or running when the application stopped cannot survive the restart, because their jobs, + // progress and cancellation tokens live only in memory, so they are marked as failed and can be triggered again. + await _luminaDbContext.LibraryScans + .Where(libraryScan => libraryScan.Status == LibraryScanJobStatus.Pending || libraryScan.Status == LibraryScanJobStatus.Running) + .ExecuteUpdateAsync(setters => setters.SetProperty(libraryScan => libraryScan.Status, LibraryScanJobStatus.Failed), cancellationToken).ConfigureAwait(false); + return Result.Updated; + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs index 2c5c87fb..8a4ddcef 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs @@ -169,6 +169,29 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR return paths.ToList(); } + /// + /// Gets the paths of the media library scan staging results of the current scan that are new or changed, meaning they need their content hashed + /// and their metadata extracted. + /// + /// The unique identifier of the media library scan whose staging result paths are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the paths of the staging results that need rehashing, or an error. + public async Task>> GetPathsNeedingRehashAsync(Guid scanId, CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); + const string GET_PATHS_SQL = """ + SELECT Path + FROM LibraryScanStagingResults + WHERE LibraryScanId = @scanId + AND NeedsRehash = 1; + """; + + CommandDefinition command = new(GET_PATHS_SQL, new { scanId }, cancellationToken: cancellationToken); + + IEnumerable paths = await connection.QueryAsync(command).ConfigureAwait(false); + return paths.ToList(); + } + /// /// Updates the content hashes of the provided media library scan staging results. /// diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs index ca219011..cddee8c2 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using System; @@ -37,6 +38,19 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(MediaContributorEntity contributor, CancellationToken cancellationToken) { + bool doesContributorExist = await _luminaDbContext.MediaContributors + .AnyAsync(repositoryContributor => repositoryContributor.Id == contributor.Id, cancellationToken: cancellationToken) + .ConfigureAwait(false); + if (doesContributorExist) + return Errors.MediaContributor.MediaContributorAlreadyExists; + + // A contributor is unique by its display name, so the same person can never be registered twice under different spellings of the same name. + bool doesContributorNameExist = await _luminaDbContext.MediaContributors + .AnyAsync(repositoryContributor => EF.Functions.Collate(repositoryContributor.DisplayName, "NOCASE") == contributor.DisplayName, cancellationToken: cancellationToken) + .ConfigureAwait(false); + if (doesContributorNameExist) + return Errors.MediaContributor.MediaContributorAlreadyExists; + _luminaDbContext.MediaContributors.Add(contributor); return Result.Created; } @@ -54,8 +68,19 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository // the comparison is case-insensitive, so that "Stephen King" and "stephen king" are never treated as distinct contributors string normalizedDisplayName = displayName.ToLowerInvariant(); + // Contributors added earlier in the same unit of work are not returned by a database query, so the change tracker is consulted + // first; without this, the same contributor discovered for several items of the same save would be inserted more than once and + // violate the unique index on the display name. + MediaContributorEntity? trackedContributor = _luminaDbContext.MediaContributors.Local + .FirstOrDefault(contributor => contributor.DisplayName.ToLowerInvariant() == normalizedDisplayName); + if (trackedContributor is not null) + return trackedContributor; + + // The lookup must use the same case-insensitive collation as the unique index on the display name, so that a name whose case is + // not folded by the storage medium (for example one that starts with a non-ASCII uppercase letter) is still matched, instead of + // being inserted again and violating the unique index. MediaContributorEntity? existingContributor = await _luminaDbContext.MediaContributors - .FirstOrDefaultAsync(contributor => contributor.DisplayName.ToLower() == normalizedDisplayName, cancellationToken) + .FirstOrDefaultAsync(contributor => EF.Functions.Collate(contributor.DisplayName, "NOCASE") == displayName, cancellationToken) .ConfigureAwait(false); if (existingContributor is not null) return existingContributor; diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs index a4d6a119..c0f21bbb 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs @@ -8,9 +8,12 @@ using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -170,6 +173,24 @@ internal sealed class AlbumRepository : IAlbumRepository shouldReplace: (existingContributor, incomingContributor) => false, createNew: incomingContributor => incomingContributor); + // The types of the release are owned value objects whose value is also their identity, so a match means there is nothing to change. + CollectionReconciler.Reconcile( + foundAlbum.ReleaseTypes, + data.ReleaseTypes, + existingReleaseType => existingReleaseType.ReleaseType, + incomingReleaseType => incomingReleaseType.ReleaseType, + shouldReplace: (existingReleaseType, incomingReleaseType) => false, + createNew: incomingReleaseType => incomingReleaseType); + + // The catalog numbers of the release are owned value objects whose value is also their identity, so a match means there is nothing to change. + CollectionReconciler.Reconcile( + foundAlbum.CatalogNumbers, + data.CatalogNumbers, + existingCatalogNumber => existingCatalogNumber.CatalogNumber, + incomingCatalogNumber => incomingCatalogNumber.CatalogNumber, + shouldReplace: (existingCatalogNumber, incomingCatalogNumber) => false, + createNew: incomingCatalogNumber => incomingCatalogNumber); + return Result.Updated; } @@ -297,4 +318,152 @@ internal sealed class AlbumRepository : IAlbumRepository NumberOfPages = numberOfPages }; } + + /// + /// Gets the album of the artist identified by that has the provided . + /// + /// The Id of the artist whose album is retrieved. + /// The title of the album to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either the with the provided title, or an error. + public async Task> GetByTitleAsync(Guid artistId, string title, CancellationToken cancellationToken) + { + AlbumEntity? album = await _luminaDbContext.Albums + .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId && repositoryAlbum.Title == title, cancellationToken).ConfigureAwait(false); + return album; + } + + /// + /// Gets the album of the artist identified by that owns a track stored in the provided . + /// + /// The Id of the artist whose album is retrieved. + /// The file system path of the album directory the album owns. + /// Cancellation token that can be used to stop the execution. + /// An containing either the owning the directory, or an error. + public async Task> GetByTrackDirectoryAsync(Guid artistId, string directoryPath, CancellationToken cancellationToken) + { + // The trailing separator is part of the prefix, so a directory whose name is a prefix of another directory does not match it. + string directoryPrefix = directoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar; + AlbumEntity? album = await _luminaDbContext.Albums + .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId + && repositoryAlbum.Tracks.Any(track => track.Path.StartsWith(directoryPrefix)), cancellationToken).ConfigureAwait(false); + return album; + } + + /// + /// Deletes the album identified by , together with its tracks and its contributions, by the database cascade. + /// + /// The Id of the album to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + AlbumEntity? album = await _luminaDbContext.Albums + .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == id, cancellationToken).ConfigureAwait(false); + if (album is null) + return Errors.Music.AlbumNotFound; + + _luminaDbContext.Albums.Remove(album); + return Result.Deleted; + } + + /// + /// Gets the number of albums of the media library identified by whose metadata has not been enriched yet. + /// + /// The Id of the media library whose albums are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of albums needing their metadata enriched, or an error. + public async Task> GetAlbumsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Albums + .CountAsync(album => album.LibraryId == libraryId && album.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the number of albums of the media library identified by whose artwork has not been resolved yet. + /// + /// The Id of the media library whose albums are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of albums needing their artwork resolved, or an error. + public async Task> GetAlbumsNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Albums + .CountAsync(album => album.LibraryId == libraryId + && !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Album + && musicArtwork.OwnerId == album.Id + && (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)), cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets a page of the albums of the media library identified by whose artwork has not been resolved yet, + /// together with their artist, ordered by Id, excluding the provided albums. + /// + /// The Id of the media library whose albums are retrieved. + /// The Ids of the albums that were already processed in the current run and must not be retrieved again. + /// The maximum number of albums to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of albums needing their artwork resolved, or an error. + public async Task>> GetAlbumsNeedingArtworkAsync(Guid libraryId, IReadOnlyCollection excludedAlbumIds, int pageSize, CancellationToken cancellationToken) + { + List excludedIds = [.. excludedAlbumIds]; + return await _luminaDbContext.Albums + .AsNoTracking() + .Include(album => album.Artist) + .Where(album => album.LibraryId == libraryId + && !excludedIds.Contains(album.Id) + && !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Album + && musicArtwork.OwnerId == album.Id + && (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable))) + .OrderBy(album => album.Id) + .Take(pageSize) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the file system path of one track of each of the albums identified by , keyed by the Id of the album. + /// + /// The Ids of the albums whose track path is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the file system path of a track of each album, or an error. + public async Task>> GetFirstTrackPathsByAlbumIdsAsync(IReadOnlyCollection albumIds, CancellationToken cancellationToken) + { + List albumIdsList = [.. albumIds]; + if (albumIdsList.Count == 0) + return new Dictionary(); + + List rows = await _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => albumIdsList.Contains(track.AlbumId)) + .OrderBy(track => track.AlbumId) + .ThenBy(track => track.Path) + .Select(track => new AlbumTrackPathRow(track.AlbumId, track.Path)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + // Only one track path is needed per album, so the first one, in the deterministic order above, is kept for each album. + Dictionary firstTrackPaths = []; + foreach (AlbumTrackPathRow row in rows) + firstTrackPaths.TryAdd(row.AlbumId, row.Path); + return firstTrackPaths; + } + + /// + /// Resets the metadata enrichment status of all the albums of the media library identified by . + /// + /// The Id of the media library whose albums are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + { + await _luminaDbContext.Albums + .Where(album => album.LibraryId == libraryId) + .ExecuteUpdateAsync(setters => setters.SetProperty(album => album.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); + return Result.Updated; + } + + /// + /// The file system path of one track of an album, used to describe the album in an artwork lookup. + /// + /// The Id of the album the track belongs to. + /// The file system path of the track. + private sealed record AlbumTrackPathRow(Guid AlbumId, string Path); } diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs index 7387003e..fea91e76 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs @@ -11,7 +11,9 @@ using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -72,7 +74,7 @@ internal sealed class ArtistRepository : IArtistRepository // neither a stored row nor a name shared by several albums or tracks of the same request is tracked more than once. Result> resolveTagsResult = await SharedReferenceResolver.ResolveAsync( _luminaDbContext, - artist.Albums.SelectMany(album => album.Tags).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))), + artist.Tags.Concat(artist.Albums.SelectMany(album => album.Tags)).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))), Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); if (resolveTagsResult.IsFailure) @@ -80,12 +82,15 @@ internal sealed class ArtistRepository : IArtistRepository Result> resolveGenresResult = await SharedReferenceResolver.ResolveAsync( _luminaDbContext, - artist.Albums.SelectMany(album => album.Genres).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))), + artist.Genres.Concat(artist.Albums.SelectMany(album => album.Genres)).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))), Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); if (resolveGenresResult.IsFailure) return resolveGenresResult.Errors; + artist.Tags = [.. SharedReferenceResolver.Normalize(artist.Tags, resolveTagsResult.Value)]; + artist.Genres = [.. SharedReferenceResolver.Normalize(artist.Genres, resolveGenresResult.Value)]; + foreach (AlbumEntity album in artist.Albums) { album.Tags = [.. SharedReferenceResolver.Normalize(album.Tags, resolveTagsResult.Value)]; @@ -113,6 +118,8 @@ internal sealed class ArtistRepository : IArtistRepository // The whole aggregate is loaded once, including every collection that the album and track repositories reconcile, so that those repositories can apply the // edit to the already tracked children instead of loading each album and each track again. ArtistEntity? foundArtist = await _luminaDbContext.Artists + .Include(repositoryArtist => repositoryArtist.Tags) + .Include(repositoryArtist => repositoryArtist.Genres) .Include(repositoryArtist => repositoryArtist.Contributors) .Include(repositoryArtist => repositoryArtist.Albums) .ThenInclude(album => album.Tags) @@ -160,6 +167,47 @@ internal sealed class ArtistRepository : IArtistRepository shouldReplace: (existingContributor, incomingContributor) => false, createNew: incomingContributor => incomingContributor); + // The tags and the genres of the artist are shared across the whole database, so the stored rows whose names already exist are reused. + Result reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundArtist.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileTagsResult.IsFailure) + return reconcileTagsResult.Errors; + Result reconcileGenresResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundArtist.Genres, data.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileGenresResult.IsFailure) + return reconcileGenresResult.Errors; + + // The ratings, the aliases and the identifiers of the artist are owned value objects with no identity anyone could reference, so a changed value is replaced as a whole. + CollectionReconciler.Reconcile( + foundArtist.Ratings, + data.Ratings, + existingRating => existingRating.Source?.ToString() ?? string.Empty, + incomingRating => incomingRating.Source?.ToString() ?? string.Empty, + shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating), + createNew: incomingRating => incomingRating); + + CollectionReconciler.Reconcile( + foundArtist.Aliases, + data.Aliases, + existingAlias => existingAlias.Name, + incomingAlias => incomingAlias.Name, + shouldReplace: (existingAlias, incomingAlias) => !existingAlias.Equals(incomingAlias), + createNew: incomingAlias => incomingAlias); + + CollectionReconciler.Reconcile( + foundArtist.Ipis, + data.Ipis, + existingIpi => existingIpi.Value, + incomingIpi => incomingIpi.Value, + shouldReplace: (existingIpi, incomingIpi) => false, + createNew: incomingIpi => incomingIpi); + + CollectionReconciler.Reconcile( + foundArtist.Isnis, + data.Isnis, + existingIsni => existingIsni.Value, + incomingIsni => incomingIsni.Value, + shouldReplace: (existingIsni, incomingIsni) => false, + createNew: incomingIsni => incomingIsni); + // A track is unique within its library by its file system path, so a track that is about to be inserted during this update can never reference a file // that is already registered, nor a file that another track of the same update already references. The check runs before anything is written. List newTrackPaths = [.. GetNewTrackPaths(foundArtist, data)]; @@ -171,19 +219,22 @@ internal sealed class ArtistRepository : IArtistRepository // and a name that is already stored is reused, before the album and track repositories reconcile their own collections. Result> resolveTagsResult = await SharedReferenceResolver.ResolveAsync( _luminaDbContext, - data.Albums.SelectMany(album => album.Tags).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))), + data.Tags.Concat(data.Albums.SelectMany(album => album.Tags)).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))), Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); if (resolveTagsResult.IsFailure) return resolveTagsResult.Errors; Result> resolveGenresResult = await SharedReferenceResolver.ResolveAsync( _luminaDbContext, - data.Albums.SelectMany(album => album.Genres).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))), + data.Genres.Concat(data.Albums.SelectMany(album => album.Genres)).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))), Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); if (resolveGenresResult.IsFailure) return resolveGenresResult.Errors; + data.Tags = [.. SharedReferenceResolver.Normalize(data.Tags, resolveTagsResult.Value)]; + data.Genres = [.. SharedReferenceResolver.Normalize(data.Genres, resolveGenresResult.Value)]; + foreach (AlbumEntity dataAlbum in data.Albums) { dataAlbum.Tags = [.. SharedReferenceResolver.Normalize(dataAlbum.Tags, resolveTagsResult.Value)]; @@ -324,6 +375,8 @@ internal sealed class ArtistRepository : IArtistRepository if (shouldIncludeNavigationProperties) { query = query + .Include(artist => artist.Tags) + .Include(artist => artist.Genres) .Include(artist => artist.Contributors) .Include(artist => artist.Albums) .ThenInclude(album => album.Ratings) @@ -393,6 +446,8 @@ internal sealed class ArtistRepository : IArtistRepository if (shouldIncludeNavigationProperties) { artistsQuery = artistsQuery + .Include(artist => artist.Tags) + .Include(artist => artist.Genres) .Include(artist => artist.Contributors) .Include(artist => artist.Albums) .ThenInclude(album => album.Ratings) @@ -587,4 +642,155 @@ internal sealed class ArtistRepository : IArtistRepository : artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id), }; } + + /// + /// Gets the artist of the library identified by that has the provided . + /// + /// The Id of the library whose artist is retrieved. + /// The name of the artist to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either the with the provided name, or an error. + public async Task> GetByNameAsync(Guid libraryId, string name, CancellationToken cancellationToken) + { + ArtistEntity? artist = await _luminaDbContext.Artists + .FirstOrDefaultAsync(repositoryArtist => repositoryArtist.LibraryId == libraryId && repositoryArtist.Name == name, cancellationToken).ConfigureAwait(false); + return artist; + } + + /// + /// Gets a page of the artists of the media library identified by whose metadata has not been enriched yet, + /// together with their albums and tracks and the collections needed to enrich them, ordered by name, using keyset pagination. + /// + /// The Id of the media library whose artists are retrieved. + /// The name of the last retrieved artist, used for keyset pagination. Pass to get the first page. + /// The maximum number of artists to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of artists needing their metadata enriched, or an error. + public async Task>> GetArtistsNeedingMetadataAsync(Guid libraryId, string? lastName, int pageSize, CancellationToken cancellationToken) + { + return await _luminaDbContext.Artists + .Include(artist => artist.Area) + .Include(artist => artist.BeginArea) + .Include(artist => artist.EndArea) + .Include(artist => artist.Aliases) + .Include(artist => artist.Ipis) + .Include(artist => artist.Isnis) + .Include(artist => artist.Genres) + .Include(artist => artist.Tags) + .Include(artist => artist.Ratings) + .Include(artist => artist.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.ReleaseTypes) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Genres) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tags) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Ratings) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Genres) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Tags) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Ratings) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Moods) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Isrcs) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.WorkLanguages) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.WorkIswcs) + .AsSplitQuery() + .Where(artist => artist.LibraryId == libraryId + && (artist.MetadataStatus != MetadataStatus.Enriched + || artist.Albums.Any(album => album.MetadataStatus != MetadataStatus.Enriched) + || artist.Albums.Any(album => album.Tracks.Any(track => track.MetadataStatus != MetadataStatus.Enriched))) + && (lastName == null || artist.Name.CompareTo(lastName) > 0)) + .OrderBy(artist => artist.Name) + .Take(pageSize) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the number of artists of the media library identified by whose metadata has not been enriched yet. + /// + /// The Id of the media library whose artists are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of artists needing their metadata enriched, or an error. + public async Task> GetArtistsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Artists + .CountAsync(artist => artist.LibraryId == libraryId + && (artist.MetadataStatus != MetadataStatus.Enriched + || artist.Albums.Any(album => album.MetadataStatus != MetadataStatus.Enriched) + || artist.Albums.Any(album => album.Tracks.Any(track => track.MetadataStatus != MetadataStatus.Enriched))), cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the number of artists of the media library identified by whose artwork has not been resolved yet. + /// + /// The Id of the media library whose artists are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of artists needing their artwork resolved, or an error. + public async Task> GetArtistsNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Artists + .CountAsync(artist => artist.LibraryId == libraryId + && !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Artist + && musicArtwork.OwnerId == artist.Id + && (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)), cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets a page of the artists of the media library identified by whose artwork has not been resolved yet, + /// together with their albums and tracks, ordered by name, using keyset pagination. + /// + /// The Id of the media library whose artists are retrieved. + /// The name of the last retrieved artist, used for keyset pagination. Pass to get the first page. + /// The maximum number of artists to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of artists needing their artwork resolved, or an error. + public async Task>> GetArtistsNeedingArtworkAsync(Guid libraryId, string? lastName, int pageSize, CancellationToken cancellationToken) + { + return await _luminaDbContext.Artists + .AsNoTracking() + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .AsSplitQuery() + .Where(artist => artist.LibraryId == libraryId + && !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Artist + && musicArtwork.OwnerId == artist.Id + && (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)) + && (lastName == null || artist.Name.CompareTo(lastName) > 0)) + .OrderBy(artist => artist.Name) + .Take(pageSize) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Resets the metadata enrichment status of all the artists of the media library identified by . + /// + /// The Id of the media library whose artists are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + { + await _luminaDbContext.Artists + .Where(artist => artist.LibraryId == libraryId) + .ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); + return Result.Updated; + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs new file mode 100644 index 00000000..ceb8f38e --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.MusicLibrary; + +/// +/// Repository for the artwork of the music library items. +/// +internal sealed class MusicArtworkRepository : IMusicArtworkRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public MusicArtworkRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a range of pieces of artwork of music library items. + /// + /// The pieces of artwork to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public Task> InsertRangeAsync(IReadOnlyCollection artwork, CancellationToken cancellationToken) + { + if (artwork.Count > 0) + _luminaDbContext.MusicArtwork.AddRange(artwork); + return Task.FromResult>(Result.Created); + } + + /// + /// Gets the pieces of artwork owned by the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken) + { + IReadOnlyList artwork = await _luminaDbContext.MusicArtwork + .AsNoTracking() + .Where(musicArtwork => musicArtwork.OwnerType == ownerType && musicArtwork.OwnerId == ownerId) + .OrderBy(musicArtwork => musicArtwork.ArtworkType) + .ThenBy(musicArtwork => musicArtwork.Ordinal) + .ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From(artwork); + } + + /// + /// Deletes all the pieces of artwork owned by the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken) + { + await _luminaDbContext.MusicArtwork + .Where(musicArtwork => musicArtwork.OwnerType == ownerType && musicArtwork.OwnerId == ownerId) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + return Result.Deleted; + } + + /// + /// Resets the artwork enrichment status of all the pieces of artwork owned by the music library items of the media library identified by . + /// + /// The Id of the media library whose artwork is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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. + List artistIds = await _luminaDbContext.Artists + .Where(artist => artist.LibraryId == libraryId) + .Select(artist => artist.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List albumIds = await _luminaDbContext.Albums + .Where(album => album.LibraryId == libraryId) + .Select(album => album.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List trackIds = await _luminaDbContext.Tracks + .Where(track => track.LibraryId == libraryId) + .Select(track => track.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + await _luminaDbContext.MusicArtwork + .Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist && artistIds.Contains(musicArtwork.OwnerId)) + || (musicArtwork.OwnerType == MusicArtworkOwnerType.Album && albumIds.Contains(musicArtwork.OwnerId)) + || (musicArtwork.OwnerType == MusicArtworkOwnerType.Track && trackIds.Contains(musicArtwork.OwnerId))) + .ExecuteUpdateAsync(setters => setters.SetProperty(musicArtwork => musicArtwork.Status, ArtworkStatus.Pending), cancellationToken).ConfigureAwait(false); + return Result.Updated; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepository.cs new file mode 100644 index 00000000..f2810e93 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepository.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.MusicLibrary; + +/// +/// Repository for the music metadata staged during a media library scan. +/// +internal sealed class MusicLibraryScanItemMetadataRepository : IMusicLibraryScanItemMetadataRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public MusicLibraryScanItemMetadataRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a range of staged music metadata items. + /// + /// The staged music metadata items to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public Task> InsertRangeAsync(IReadOnlyCollection items, CancellationToken cancellationToken) + { + if (items.Count > 0) + _luminaDbContext.MusicLibraryScanItemMetadata.AddRange(items); + return Task.FromResult>(Result.Created); + } + + /// + /// Gets all the staged music metadata items of the media library scan identified by . + /// + /// The Id of the media library scan whose staged music metadata is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByScanIdAsync(Guid scanId, CancellationToken cancellationToken) + { + IReadOnlyList items = await _luminaDbContext.MusicLibraryScanItemMetadata + .AsNoTracking() + .Where(musicMetadata => musicMetadata.LibraryScanId == scanId) + .OrderBy(musicMetadata => musicMetadata.Path) + .ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From(items); + } + + /// + /// Deletes all the staged music metadata items of the media library scan identified by . + /// + /// The Id of the media library scan whose staged music metadata is deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByScanIdAsync(Guid scanId, CancellationToken cancellationToken) + { + await _luminaDbContext.MusicLibraryScanItemMetadata + .Where(musicMetadata => musicMetadata.LibraryScanId == scanId) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + return Result.Deleted; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index de46fe87..4837ccf2 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -8,6 +8,7 @@ using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -175,6 +176,23 @@ internal sealed class TrackRepository : ITrackRepository shouldReplace: (existingIsrc, incomingIsrc) => false, createNew: incomingIsrc => incomingIsrc); + // The languages and the ISWCs of the work are owned value objects whose value is also their identity, so a match means there is nothing to change. + CollectionReconciler.Reconcile( + foundTrack.WorkLanguages, + data.WorkLanguages, + existingWorkLanguage => existingWorkLanguage.LanguageCode, + incomingWorkLanguage => incomingWorkLanguage.LanguageCode, + shouldReplace: (existingWorkLanguage, incomingWorkLanguage) => !existingWorkLanguage.Equals(incomingWorkLanguage), + createNew: incomingWorkLanguage => incomingWorkLanguage); + + CollectionReconciler.Reconcile( + foundTrack.WorkIswcs, + data.WorkIswcs, + existingWorkIswc => existingWorkIswc.Value, + incomingWorkIswc => incomingWorkIswc.Value, + shouldReplace: (existingWorkIswc, incomingWorkIswc) => false, + createNew: incomingWorkIswc => incomingWorkIswc); + return Result.Updated; } @@ -286,4 +304,107 @@ internal sealed class TrackRepository : ITrackRepository NumberOfPages = numberOfPages }; } + + /// + /// Gets the track of the library identified by that is stored at the provided . + /// + /// The Id of the library whose track is retrieved. + /// The file system path of the track to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either the stored at the provided path, or an error. + public async Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken) + { + TrackEntity? track = await _luminaDbContext.Tracks + .FirstOrDefaultAsync(repositoryTrack => repositoryTrack.LibraryId == libraryId && repositoryTrack.Path == path, cancellationToken).ConfigureAwait(false); + return track; + } + + /// + /// Deletes the track identified by , together with its owned collections and contributions, by the database cascade. + /// + /// The Id of the track to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + TrackEntity? track = await _luminaDbContext.Tracks + .FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == id, cancellationToken).ConfigureAwait(false); + if (track is null) + return Errors.Music.TrackNotFound; + + _luminaDbContext.Tracks.Remove(track); + return Result.Deleted; + } + + /// + /// Resets the enrichment state of the tracks stored at the provided in the media library identified by + /// , together with their albums and artists. + /// + /// The Id of the media library whose tracks are reset. + /// The file system paths of the tracks whose enrichment state is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken) + { + List pathList = [.. paths]; + if (pathList.Count == 0) + return Result.Updated; + + // The tracks stored at the changed paths are reset, together with the albums and the artists they belong to, because the metadata of the whole release is re-evaluated. + List trackIds = await _luminaDbContext.Tracks + .Where(track => track.LibraryId == libraryId && pathList.Contains(track.Path)) + .Select(track => track.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (trackIds.Count == 0) + return Result.Updated; + + List albumIds = await _luminaDbContext.Tracks + .Where(track => trackIds.Contains(track.Id)) + .Select(track => track.AlbumId) + .Distinct() + .ToListAsync(cancellationToken).ConfigureAwait(false); + List artistIds = await _luminaDbContext.Albums + .Where(album => albumIds.Contains(album.Id)) + .Select(album => album.ArtistId) + .Distinct() + .ToListAsync(cancellationToken).ConfigureAwait(false); + + await _luminaDbContext.Tracks + .Where(track => trackIds.Contains(track.Id)) + .ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); + await _luminaDbContext.Albums + .Where(album => albumIds.Contains(album.Id)) + .ExecuteUpdateAsync(setters => setters.SetProperty(album => album.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); + await _luminaDbContext.Artists + .Where(artist => artistIds.Contains(artist.Id)) + .ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); + + return Result.Updated; + } + + /// + /// Gets the number of tracks of the media library identified by whose metadata has not been enriched yet. + /// + /// The Id of the media library whose tracks are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of tracks needing their metadata enriched, or an error. + public async Task> GetTracksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Tracks + .CountAsync(track => track.LibraryId == libraryId && track.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resets the metadata enrichment status of all the tracks of the media library identified by . + /// + /// The Id of the media library whose tracks are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + { + await _luminaDbContext.Tracks + .Where(track => track.LibraryId == libraryId) + .ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); + return Result.Updated; + } } diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index c49fa627..5e0f4b86 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -198,7 +198,9 @@ public class DataSeedService : IDataSeedService // Repair the installed themes whose files are missing, at every application startup. CreateDefaultScheduledJob("Repair themes at startup", ScheduledTaskType.RepairThemes, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId), // Clean the execution history of the scheduled jobs, keeping only the executions of the past month, at every application startup. - CreateDefaultScheduledJob("Clean scheduled job execution history at startup", ScheduledTaskType.CleanScheduledJobExecutionHistory, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId) + CreateDefaultScheduledJob("Clean scheduled job execution history at startup", ScheduledTaskType.CleanScheduledJobExecutionHistory, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId), + // Clean the technical data that is no longer valid, at every application startup. + CreateDefaultScheduledJob("Technical data cleanup at startup", ScheduledTaskType.TechnicalDataCleanup, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId) ]; foreach (ScheduledJobEntity defaultScheduledJob in defaultScheduledJobs) { diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index f84beb77..fcbe9802 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -24,6 +24,8 @@ public class LuminaDbContext : DbContext public virtual DbSet Artists { get; set; } = null!; public virtual DbSet Albums { get; set; } = null!; public virtual DbSet Tracks { get; set; } = null!; + public virtual DbSet MusicArtwork { get; set; } = null!; + public virtual DbSet MusicLibraryScanItemMetadata { get; set; } = null!; public virtual DbSet Users { get; set; } = null!; public virtual DbSet UserSettings { get; set; } = null!; public virtual DbSet Libraries { get; set; } = null!; diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index a4064637..fd78d4bf 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -46,6 +46,8 @@ public class UnitOfWork : IUnitOfWork, IDisposable private IArtistRepository? _artistRepository; private IAlbumRepository? _albumRepository; private ITrackRepository? _trackRepository; + private IMusicArtworkRepository? _musicArtworkRepository; + private IMusicLibraryScanItemMetadataRepository? _musicLibraryScanItemMetadataRepository; private IMediaContributorRepository? _mediaContributorRepository; private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository; private ILibraryRepository? _libraryRepository; @@ -159,6 +161,30 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + /// + /// Gets the repository for the artwork of the music library items. + /// + public IMusicArtworkRepository MusicArtworkRepository + { + get + { + _musicArtworkRepository ??= new MusicArtworkRepository(_luminaDbContext); + return _musicArtworkRepository; + } + } + + /// + /// Gets the repository for the music metadata staged during a media library scan. + /// + public IMusicLibraryScanItemMetadataRepository MusicLibraryScanItemMetadataRepository + { + get + { + _musicLibraryScanItemMetadataRepository ??= new MusicLibraryScanItemMetadataRepository(_luminaDbContext); + return _musicLibraryScanItemMetadataRepository; + } + } + public IMediaContributorRepository MediaContributorRepository { get diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtistGender.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtistGender.cs new file mode 100644 index 00000000..528dd181 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtistGender.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the gender of a music artist, applicable only to artists that are persons or characters. +/// +[DebuggerDisplay("{ToString()}")] +public enum MusicArtistGender +{ + /// + /// The artist identifies as male. + /// + Male, + + /// + /// The artist identifies as female. + /// + Female, + + /// + /// The artist identifies with a gender other than male or female. + /// + Other, + + /// + /// The gender of the artist is not applicable, or is deliberately not stated. + /// + NotApplicable +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtistType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtistType.cs new file mode 100644 index 00000000..230cdf62 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtistType.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the type of a music artist, describing whether the artist is an individual, an ensemble, or something else. +/// +[DebuggerDisplay("{ToString()}")] +public enum MusicArtistType +{ + /// + /// The artist is an individual person. + /// + Person, + + /// + /// The artist is a group of people that may or may not have a distinctive name. + /// + Group, + + /// + /// The artist is an orchestra, a large instrumental ensemble. + /// + Orchestra, + + /// + /// The artist is a choir or chorus, a large vocal ensemble. + /// + Choir, + + /// + /// The artist is an individual fictional character. + /// + Character, + + /// + /// The type of the artist does not fit into any of the known categories. + /// + Other +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs new file mode 100644 index 00000000..29ed3503 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the type of the music library item that owns a piece of artwork. +/// +[DebuggerDisplay("{ToString()}")] +public enum MusicArtworkOwnerType +{ + /// + /// The artwork belongs to an artist. + /// + Artist, + + /// + /// The artwork belongs to an album. + /// + Album, + + /// + /// The artwork belongs to a track. + /// + Track +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicReleasePackaging.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicReleasePackaging.cs new file mode 100644 index 00000000..aa2f5d2c --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicReleasePackaging.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the outermost physical packaging of a music release. +/// +[DebuggerDisplay("{ToString()}")] +public enum MusicReleasePackaging +{ + /// + /// The release is a book with a sleeve containing a medium, usually a compact disc. + /// + Book, + + /// + /// The release is a box with a lid or an opening that contains the medium and other packaging, like posters and a booklet. + /// + Box, + + /// + /// The release is a sleeve made of paper, paperboard, or cardboard. + /// + CardboardPaperSleeve, + + /// + /// The release is a regular plastic case for a cassette. + /// + CassetteCase, + + /// + /// The release is a minimalistic plastic case where the back and the front are kept together by a small hinge. + /// + ClamshellCase, + + /// + /// The release is a bounded booklet, usually in hardcover, with a sleeve bound to its spine that houses a compact disc. + /// + Digibook, + + /// + /// The release is a folded cardboard compact disc packaging that has a small pocket on one side for the disc. + /// + Digifile, + + /// + /// The release is a folded case, typically made of coated paperboard, with one or more plastic trays glued into it. + /// + Digipak, + + /// + /// The release is a pouch-like package with an internal mechanism that pushes the contents out when the lid flap is opened. + /// + DiscboxSlider, + + /// + /// The release is a double-sided, double-width jewel case normally holding two to four compact discs. + /// + Fatbox, + + /// + /// The release is a cardboard sleeve that folds in halves, thirds, or more, and can hold multiple records, compact discs, booklets, or posters. + /// + GatefoldCover, + + /// + /// The release is the traditional compact disc case, made of hard, brittle plastic. + /// + JewelCase, + + /// + /// The release is the traditional DVD case, made of soft plastic with a thin transparent cover protecting the artwork. + /// + KeepCase, + + /// + /// The release is a large cardboard box, often used to sell compact discs in North America so that they would fit vinyl racks. + /// + Longbox, + + /// + /// The release is an often decorated metal tin containing one or more compact discs. + /// + MetalTin, + + /// + /// The release is a sleeve made entirely of plastic that holds the medium and the other parts of the album. + /// + PlasticSleeve, + + /// + /// The release is a box with openings at its two ends that contains a tray holding the medium. + /// + Slidepack, + + /// + /// The release is a thinner jewel case, commonly used for compact disc singles. + /// + SlimJewelCase, + + /// + /// The release is a four or five-sided box that surrounds a second inner package such as a jewel case. + /// + Slipcase, + + /// + /// The release is a digipak-like case held together with a snapping plastic closure. + /// + SnapCase, + + /// + /// The release is a cardboard jacket, commonly used for 8cm compact disc singles in Japan. + /// + SnapPack, + + /// + /// The release is a case similar to the regular jewel case, but with rounded corners and a latch closing mechanism. + /// + SuperJewelBox, + + /// + /// The packaging of the release does not fit into any of the known categories. + /// + Other, + + /// + /// The release has no packaging at all, which is common for digital media. + /// + None +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/ArtworkStatus.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/ArtworkStatus.cs deleted file mode 100644 index 4337752e..00000000 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/ArtworkStatus.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; - -/// -/// Enumeration for the status of the artwork enrichment of a book artwork. -/// -public enum ArtworkStatus -{ - /// - /// The artwork of the book has not been resolved yet. - /// - Pending, - - /// - /// The artwork of the book has been successfully resolved. - /// - Enriched, - - /// - /// The artwork resolution of the book failed. - /// - Failed -} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/MetadataStatus.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/MetadataStatus.cs deleted file mode 100644 index 0f3cf283..00000000 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/MetadataStatus.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; - -/// -/// Enumeration for the status of the metadata enrichment of a book. -/// -public enum MetadataStatus -{ - /// - /// The metadata of the book has not been enriched yet. - /// - Pending, - - /// - /// The metadata of the book has been successfully enriched. - /// - Enriched, - - /// - /// The metadata enrichment of the book failed. - /// - Failed -} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Common/ReleaseCountry.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Common/ReleaseCountry.cs index b8bd644f..f9b1bbab 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/Common/ReleaseCountry.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Common/ReleaseCountry.cs @@ -5,7 +5,7 @@ using System.Diagnostics; namespace Lumina.Domain.SharedKernel.Common.Enums.Common; /// -/// Enumeration for the country of a media release, using the ISO 3166-1 alpha-2 country codes. +/// Enumeration for the country of a media release, using the ISO 3166-1 alpha-2 country codes, together with the MusicBrainz special codes for releases issued across Europe or worldwide. /// [DebuggerDisplay("{ToString()}")] public enum ReleaseCountry @@ -988,5 +988,20 @@ public enum ReleaseCountry /// /// The ISO 3166-1 alpha-2 code of Zimbabwe. /// - ZW + ZW, + + /// + /// The ISO 3166-1 alpha-2 code of the Netherlands Antilles, withdrawn in 2010. + /// + AN, + + /// + /// The MusicBrainz code for a release issued across Europe. + /// + XE, + + /// + /// The MusicBrainz code for a release issued worldwide. + /// + XW } diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRole.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRole.cs index 00d63b55..316873c7 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRole.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRole.cs @@ -176,5 +176,10 @@ public enum MediaContributorRole /// /// The contributor orchestrated the music of the media item. /// - Orchestrator + Orchestrator, + + /// + /// The contributor performed the media item, without a more specific role being known. + /// + Performer } diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkStatus.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkStatus.cs new file mode 100644 index 00000000..53ad160e --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkStatus.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the status of the artwork enrichment of a media library item. +/// +[DebuggerDisplay("{ToString()}")] +public enum ArtworkStatus +{ + /// + /// The artwork of the media library item has not been resolved yet. + /// + Pending, + + /// + /// The artwork of the media library item has been successfully resolved. + /// + Enriched, + + /// + /// The artwork of the media library item was searched for, and no artwork exists for it. + /// + NotAvailable, + + /// + /// The artwork resolution of the media library item failed, because an error prevented the artwork from being retrieved. + /// + Failed +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkType.cs index eef84f22..acad1c48 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkType.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkType.cs @@ -16,5 +16,85 @@ public enum ArtworkType /// /// The main artwork of the media library item, like the cover of a book. /// - Cover + Cover, + + /// + /// The front of the artwork of the media library item, when it is stored separately from the cover. + /// + Front, + + /// + /// The back of the artwork of the media library item. + /// + Back, + + /// + /// A page of the booklet of the media library item. + /// + Booklet, + + /// + /// The artwork printed on the medium of the media library item, like a disc label. + /// + Medium, + + /// + /// The artwork printed on the tray of the media library item. + /// + Tray, + + /// + /// The artwork printed on the spine of the media library item. + /// + Spine, + + /// + /// The obi strip of the media library item. + /// + Obi, + + /// + /// The sticker of the media library item. + /// + Sticker, + + /// + /// The poster of the media library item. + /// + Poster, + + /// + /// The liner notes of the media library item. + /// + Liner, + + /// + /// A watermark carried by the artwork of the media library item. + /// + Watermark, + + /// + /// The backdrop, or fanart, of the media library item. + /// + Backdrop, + + /// + /// The banner of the media library item. + /// + Banner, + + /// + /// The logo of the media library item. + /// + Logo, + + /// + /// The thumbnail of the media library item. + /// + Thumb, + + /// + /// Any other artwork of the media library item. + /// + Other } diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/LibraryPathPartKind.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/LibraryPathPartKind.cs new file mode 100644 index 00000000..588af99f --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/LibraryPathPartKind.cs @@ -0,0 +1,82 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the kinds of parts that make up a media library path template. +/// +public enum LibraryPathPartKind +{ + /// + /// A free text part, used for arbitrary on-disk text and for the literal glue between value parts (e.g. " - "). + /// + Literal, + + /// + /// The path separator between two directories of the library structure. + /// + Separator, + + /// + /// The name of the artist the release belongs to. + /// + Artist, + + /// + /// The type of the release (e.g. Album, Single, Compilation). + /// + ReleaseType, + + /// + /// The year the release was published. + /// + ReleaseYear, + + /// + /// The title of the release. + /// + ReleaseName, + + /// + /// The number of the track on its disc. + /// + TrackNumber, + + /// + /// The title of the track. + /// + TrackName, + + /// + /// The file name extension of the track, without the leading dot. + /// + Extension, + + /// + /// The number of the disc the track belongs to. + /// + DiscNumber, + + /// + /// The name of the author of a book. + /// + Author, + + /// + /// The title of a book. + /// + Title, + + /// + /// The name of the series a book belongs to. + /// + Series, + + /// + /// The number of the book within its series. + /// + SeriesNumber, + + /// + /// The identifier Calibre assigns to a book on disk. + /// + BookId +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/LibraryPathValueType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/LibraryPathValueType.cs new file mode 100644 index 00000000..8f23a3ca --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/LibraryPathValueType.cs @@ -0,0 +1,32 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the value types captured by the typed parts of a media library path template. +/// +public enum LibraryPathValueType +{ + /// + /// The part carries no captured value, like a literal or a path separator. + /// + None, + + /// + /// The part captures a free text value. + /// + Text, + + /// + /// The part captures an integer value. + /// + Integer, + + /// + /// The part captures a four digit year. + /// + Year, + + /// + /// The part captures a value that is later resolved against an enumeration. + /// + Enum +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/MetadataStatus.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/MetadataStatus.cs new file mode 100644 index 00000000..596f5e08 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/MetadataStatus.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the status of the metadata enrichment of a media library item. +/// +[DebuggerDisplay("{ToString()}")] +public enum MetadataStatus +{ + /// + /// The metadata of the media library item has not been enriched yet. + /// + Pending, + + /// + /// The metadata of the media library item has been successfully enriched. + /// + Enriched, + + /// + /// The metadata enrichment of the media library item failed. + /// + Failed +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs index cc91f3cc..9b99d50c 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs @@ -23,5 +23,10 @@ public enum ScheduledTaskType /// /// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions. /// - CleanScheduledJobExecutionHistory + CleanScheduledJobExecutionHistory, + + /// + /// The scheduled job cleans the technical data that is no longer valid. + /// + TechnicalDataCleanup } diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index b7ce03d8..728ee2a7 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -6,7 +6,11 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics.CodeAnalysis; @@ -49,7 +53,11 @@ public static class DomainLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Lumina.Domain/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs index 906b5c69..ffff621a 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -20,10 +20,14 @@ public static partial class Errors public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound)); public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull)); public static Error CoverFileMustBeAnImage => Error.Validation(description: nameof(CoverFileMustBeAnImage)); - public static Error UnknownLibraryType => Error.Unexpected(description: nameof(UnknownLibraryType)); + public static Error UnknownLibraryType => Error.Forbidden(description: nameof(UnknownLibraryType)); public static Error PathsListCannotBeNull => Error.Validation(description: nameof(PathsListCannotBeNull)); public static Error PathsListCannotBeEmpty => Error.Validation(description: nameof(PathsListCannotBeEmpty)); public static Error TitleCannotBeEmpty => Error.Validation(description: nameof(TitleCannotBeEmpty)); public static Error TitleMustBeMaximum255CharactersLong => Error.Validation(description: nameof(TitleMustBeMaximum255CharactersLong)); + public static Error PathTemplateLiteralCannotBeEmpty => Error.Validation(description: nameof(PathTemplateLiteralCannotBeEmpty)); + public static Error PathTemplateValuePartMustContainSinglePlaceholder => Error.Validation(description: nameof(PathTemplateValuePartMustContainSinglePlaceholder)); + public static Error PathTemplatePartKindNotSupportedForLibraryType => Error.Validation(description: nameof(PathTemplatePartKindNotSupportedForLibraryType)); + public static Error PathTemplateIsNotSupportedForLibraryType => Error.Validation(description: nameof(PathTemplateIsNotSupportedForLibraryType)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs index 87d4bf7b..7c71d685 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs @@ -22,6 +22,7 @@ public static partial class Errors public static Error ContributorsListCannotBeNull => Error.Validation(description: nameof(ContributorsListCannotBeNull)); public static Error MediaContributorIdCannotBeEmpty => Error.Validation(description: nameof(MediaContributorIdCannotBeEmpty)); public static Error MediaContributorNotFound => Error.NotFound(description: nameof(MediaContributorNotFound)); + public static Error MediaContributorAlreadyExists => Error.Conflict(description: nameof(MediaContributorAlreadyExists)); public static Error UnknownMediaContributorRole => Error.Validation(description: nameof(UnknownMediaContributorRole)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Music.cs b/src/Lumina.Domain/Common/Errors/Errors.Music.cs index 42acfa31..d4cca16a 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Music.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Music.cs @@ -34,6 +34,7 @@ public static partial class Errors public static Error UnknownMusicReleaseType => Error.Validation(description: nameof(UnknownMusicReleaseType)); public static Error UnknownMusicReleaseStatus => Error.Validation(description: nameof(UnknownMusicReleaseStatus)); public static Error UnknownMusicMediaFormat => Error.Validation(description: nameof(UnknownMusicMediaFormat)); + public static Error UnknownMusicReleasePackaging => Error.Validation(description: nameof(UnknownMusicReleasePackaging)); public static Error UnknownMusicKey => Error.Validation(description: nameof(UnknownMusicKey)); public static Error CatalogNumberMustBeMaximum50CharactersLong => Error.Validation(description: nameof(CatalogNumberMustBeMaximum50CharactersLong)); public static Error TrackNotFound => Error.NotFound(description: nameof(TrackNotFound)); @@ -52,5 +53,17 @@ public static partial class Errors public static Error TheArtistDoesNotHaveTheAlbum => Error.Forbidden(description: nameof(TheArtistDoesNotHaveTheAlbum)); public static Error TheTrackIsAlreadyInTheAlbum => Error.Forbidden(description: nameof(TheTrackIsAlreadyInTheAlbum)); public static Error TheTrackIsNotInTheAlbum => Error.Forbidden(description: nameof(TheTrackIsNotInTheAlbum)); + public static Error AreaNameCannotBeEmpty => Error.Validation(description: nameof(AreaNameCannotBeEmpty)); + public static Error ArtistAliasNameCannotBeEmpty => Error.Validation(description: nameof(ArtistAliasNameCannotBeEmpty)); + public static Error ArtistAliasNameMustBeMaximum255CharactersLong => Error.Validation(description: nameof(ArtistAliasNameMustBeMaximum255CharactersLong)); + public static Error AreaNameMustBeMaximum255CharactersLong => Error.Validation(description: nameof(AreaNameMustBeMaximum255CharactersLong)); + public static Error UnknownMusicArtistType => Error.Validation(description: nameof(UnknownMusicArtistType)); + public static Error UnknownMusicArtistGender => Error.Validation(description: nameof(UnknownMusicArtistGender)); + public static Error CountryMustBeMaximum2CharactersLong => Error.Validation(description: nameof(CountryMustBeMaximum2CharactersLong)); + public static Error IpiValueCannotBeEmpty => Error.Validation(description: nameof(IpiValueCannotBeEmpty)); + public static Error IpiValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IpiValueMustBeMaximum20CharactersLong)); + public static Error IsniValueCannotBeEmpty => Error.Validation(description: nameof(IsniValueCannotBeEmpty)); + public static Error IsniValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IsniValueMustBeMaximum20CharactersLong)); + public static Error WorkTitleCannotBeEmpty => Error.Validation(description: nameof(WorkTitleCannotBeEmpty)); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs index 1326fb7d..27db4eda 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadata.cs @@ -43,6 +43,31 @@ public class AudioMetadata : BaseMetadata /// public Optional Bitrate { get; } + /// + /// Gets the AcoustID fingerprint identifier of the audio file, if applicable. + /// + public Optional AcoustId { get; } + + /// + /// Gets the ReplayGain track gain in decibels, if applicable. + /// + public Optional ReplayGainTrackGain { get; } + + /// + /// Gets the ReplayGain track peak, if applicable. + /// + public Optional ReplayGainTrackPeak { get; } + + /// + /// Gets the ReplayGain album gain in decibels, if applicable. + /// + public Optional ReplayGainAlbumGain { get; } + + /// + /// Gets the ReplayGain album peak, if applicable. + /// + public Optional ReplayGainAlbumPeak { get; } + /// /// Initializes a new instance of the class. /// @@ -60,6 +85,11 @@ public class AudioMetadata : BaseMetadata /// The genres of the audio. /// The tags associated with the audio. /// The bitrate of the audio in kbps. + /// The AcoustID fingerprint identifier of the audio file. + /// The ReplayGain track gain in decibels. + /// The ReplayGain track peak. + /// The ReplayGain album gain in decibels. + /// The ReplayGain album peak. private AudioMetadata( string title, Optional originalTitle, @@ -74,7 +104,12 @@ public class AudioMetadata : BaseMetadata Optional originalLanguage, Optional bitDepth, Optional audioCodec, - Optional bitrate) + Optional bitrate, + Optional acoustId, + Optional replayGainTrackGain, + Optional replayGainTrackPeak, + Optional replayGainAlbumGain, + Optional replayGainAlbumPeak) : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) { DurationInSeconds = durationInSeconds; @@ -83,6 +118,11 @@ public class AudioMetadata : BaseMetadata BitDepth = bitDepth; AudioCodec = audioCodec; Bitrate = bitrate; + AcoustId = acoustId; + ReplayGainTrackGain = replayGainTrackGain; + ReplayGainTrackPeak = replayGainTrackPeak; + ReplayGainAlbumGain = replayGainAlbumGain; + ReplayGainAlbumPeak = replayGainAlbumPeak; } /// @@ -102,6 +142,11 @@ public class AudioMetadata : BaseMetadata /// The genres of the audio. /// The tags associated with the audio. /// The bitrate of the audio in kbps. + /// The AcoustID fingerprint identifier of the audio file. + /// The ReplayGain track gain in decibels. + /// The ReplayGain track peak. + /// The ReplayGain album gain in decibels. + /// The ReplayGain album peak. /// /// An containing either a successfully created , or an error message. /// @@ -119,7 +164,12 @@ public class AudioMetadata : BaseMetadata Optional originalLanguage, Optional bitDepth, Optional audioCodec, - Optional bitrate) + Optional bitrate, + Optional acoustId, + Optional replayGainTrackGain, + Optional replayGainTrackPeak, + Optional replayGainAlbumGain, + Optional replayGainAlbumPeak) { return new AudioMetadata( title, @@ -135,7 +185,12 @@ public class AudioMetadata : BaseMetadata originalLanguage, bitDepth, audioCodec, - bitrate); + bitrate, + acoustId, + replayGainTrackGain, + replayGainTrackPeak, + replayGainAlbumGain, + replayGainAlbumPeak); } /// @@ -152,5 +207,10 @@ public class AudioMetadata : BaseMetadata yield return BitDepth; yield return AudioCodec; yield return Bitrate; + yield return AcoustId; + yield return ReplayGainTrackGain; + yield return ReplayGainTrackPeak; + yield return ReplayGainAlbumGain; + yield return ReplayGainAlbumPeak; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs index ea66a780..62baa2ee 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs @@ -30,6 +30,12 @@ namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLib public sealed class Artist : AggregateRoot { private readonly HashSet _contributors; + private readonly List _aliases; + private readonly List _ipis; + private readonly List _isnis; + private readonly List _genres; + private readonly List _tags; + private readonly List _ratings; private readonly List _albums; /// @@ -42,6 +48,61 @@ public sealed class Artist : AggregateRoot /// public string Name { get; private set; } + /// + /// Gets the sort name of the artist, a variant of the name used when sorting artists, if applicable. + /// + public Optional SortName { get; private set; } + + /// + /// Gets the disambiguation comment of the artist, used to distinguish artists with the same name, if applicable. + /// + public Optional Disambiguation { get; private set; } + + /// + /// Gets the type of the artist, describing whether it is a person, a group, or something else, if applicable. + /// + public Optional Type { get; private set; } + + /// + /// Gets the gender of the artist, applicable only to artists that are persons or characters, if applicable. + /// + public Optional Gender { get; private set; } + + /// + /// Gets the ISO 3166-1 alpha-2 code of the country the artist is associated with, if applicable. + /// + public Optional Country { get; private set; } + + /// + /// Gets the area the artist is primarily identified with, if applicable. + /// + public Optional Area { get; private set; } + + /// + /// Gets the area the artist began in, if applicable. + /// + public Optional BeginArea { get; private set; } + + /// + /// Gets the area the artist ended in, if applicable. + /// + public Optional EndArea { get; private set; } + + /// + /// Gets the date the artist started existing, if applicable. + /// + public Optional LifeSpanBegin { get; private set; } + + /// + /// Gets the date the artist stopped existing, if applicable. + /// + public Optional LifeSpanEnd { get; private set; } + + /// + /// Gets a value indicating whether the artist no longer exists. + /// + public bool IsEnded { get; private set; } + /// /// Gets the website of the artist, if applicable. /// @@ -52,6 +113,36 @@ public sealed class Artist : AggregateRoot /// public Optional MusicBrainzArtistId { get; private set; } + /// + /// Gets the list of IPI (Interested Party Information) codes of the artist. + /// + public IReadOnlyCollection Ipis => _ipis.AsReadOnly(); + + /// + /// Gets the list of ISNI (International Standard Name Identifier) codes of the artist. + /// + public IReadOnlyCollection Isnis => _isnis.AsReadOnly(); + + /// + /// Gets the list of alternative names of the artist. + /// + public IReadOnlyCollection Aliases => _aliases.AsReadOnly(); + + /// + /// Gets the list of genres associated with the artist. + /// + public IReadOnlyCollection Genres => _genres.AsReadOnly(); + + /// + /// Gets the list of tags associated with the artist. + /// + public IReadOnlyCollection Tags => _tags.AsReadOnly(); + + /// + /// Gets the list of ratings of the artist. + /// + public IReadOnlyCollection Ratings => _ratings.AsReadOnly(); + /// /// Gets the list of the media contributors that make up the artist. /// @@ -68,8 +159,25 @@ public sealed class Artist : AggregateRoot /// The object representing the unique identifier of the artist. /// The Id of the media library this artist belongs to. /// The name of the artist. + /// The optional sort name of the artist. + /// The optional disambiguation comment of the artist. + /// The optional type of the artist. + /// The optional gender of the artist. + /// The optional ISO 3166-1 alpha-2 code of the country of the artist. + /// The optional area the artist is primarily identified with. + /// The optional area the artist began in. + /// The optional area the artist ended in. + /// The optional date the artist started existing. + /// The optional date the artist stopped existing. + /// Whether the artist no longer exists. /// The optional website of the artist. /// The optional MusicBrainz identifier of the artist. + /// The list of IPI codes of the artist. + /// The list of ISNI codes of the artist. + /// The list of alternative names of the artist. + /// The list of genres associated with the artist. + /// The list of tags associated with the artist. + /// The list of ratings of the artist. /// The list of the media contributors that make up the artist. /// The list of albums of the artist. /// The date and time when the entity was created. @@ -78,8 +186,25 @@ public sealed class Artist : AggregateRoot ArtistId id, LibraryId libraryId, string name, + Optional sortName, + Optional disambiguation, + Optional type, + Optional gender, + Optional country, + Optional area, + Optional beginArea, + Optional endArea, + Optional lifeSpanBegin, + Optional lifeSpanEnd, + bool isEnded, Optional website, Optional musicBrainzArtistId, + List ipis, + List isnis, + List aliases, + List genres, + List tags, + List ratings, List contributors, List albums, DateTime createdOnUtc, @@ -88,8 +213,25 @@ public sealed class Artist : AggregateRoot Id = id; LibraryId = libraryId; Name = name; + SortName = sortName; + Disambiguation = disambiguation; + Type = type; + Gender = gender; + Country = country; + Area = area; + BeginArea = beginArea; + EndArea = endArea; + LifeSpanBegin = lifeSpanBegin; + LifeSpanEnd = lifeSpanEnd; + IsEnded = isEnded; Website = website; MusicBrainzArtistId = musicBrainzArtistId; + _ipis = ipis; + _isnis = isnis; + _aliases = aliases; + _genres = genres; + _tags = tags; + _ratings = ratings; _contributors = [.. contributors]; _albums = albums; CreatedOnUtc = createdOnUtc; @@ -101,8 +243,25 @@ public sealed class Artist : AggregateRoot /// /// The Id of the media library this artist belongs to. /// The name of the artist. + /// The optional sort name of the artist. + /// The optional disambiguation comment of the artist. + /// The optional type of the artist. + /// The optional gender of the artist. + /// The optional ISO 3166-1 alpha-2 code of the country of the artist. + /// The optional area the artist is primarily identified with. + /// The optional area the artist began in. + /// The optional area the artist ended in. + /// The optional date the artist started existing. + /// The optional date the artist stopped existing. + /// Whether the artist no longer exists. /// The optional website of the artist. /// The optional MusicBrainz identifier of the artist. + /// The list of IPI codes of the artist. + /// The list of ISNI codes of the artist. + /// The list of alternative names of the artist. + /// The list of genres associated with the artist. + /// The list of tags associated with the artist. + /// The list of ratings of the artist. /// The list of the media contributors that make up the artist. /// The list of albums of the artist. /// @@ -111,8 +270,25 @@ public sealed class Artist : AggregateRoot public static Result Create( LibraryId libraryId, string name, + Optional sortName, + Optional disambiguation, + Optional type, + Optional gender, + Optional country, + Optional area, + Optional beginArea, + Optional endArea, + Optional lifeSpanBegin, + Optional lifeSpanEnd, + bool isEnded, Optional website, Optional musicBrainzArtistId, + List ipis, + List isnis, + List aliases, + List genres, + List tags, + List ratings, List contributors, List albums) { @@ -125,8 +301,25 @@ public sealed class Artist : AggregateRoot ArtistId.CreateUnique(), libraryId, name, + sortName, + disambiguation, + type, + gender, + country, + area, + beginArea, + endArea, + lifeSpanBegin, + lifeSpanEnd, + isEnded, website, musicBrainzArtistId, + ipis, + isnis, + aliases, + genres, + tags, + ratings, contributors, albums, DateTime.UtcNow, // TODO: should be IDateTimeProvider. @@ -139,8 +332,25 @@ public sealed class Artist : AggregateRoot /// The object representing the unique identifier of the artist. /// The Id of the media library this artist belongs to. /// The name of the artist. + /// The optional sort name of the artist. + /// The optional disambiguation comment of the artist. + /// The optional type of the artist. + /// The optional gender of the artist. + /// The optional ISO 3166-1 alpha-2 code of the country of the artist. + /// The optional area the artist is primarily identified with. + /// The optional area the artist began in. + /// The optional area the artist ended in. + /// The optional date the artist started existing. + /// The optional date the artist stopped existing. + /// Whether the artist no longer exists. /// The optional website of the artist. /// The optional MusicBrainz identifier of the artist. + /// The list of IPI codes of the artist. + /// The list of ISNI codes of the artist. + /// The list of alternative names of the artist. + /// The list of genres associated with the artist. + /// The list of tags associated with the artist. + /// The list of ratings of the artist. /// The list of the media contributors that make up the artist. /// The list of albums of the artist. /// The date and time when the entity was created. @@ -152,8 +362,25 @@ public sealed class Artist : AggregateRoot ArtistId id, LibraryId libraryId, string name, + Optional sortName, + Optional disambiguation, + Optional type, + Optional gender, + Optional country, + Optional area, + Optional beginArea, + Optional endArea, + Optional lifeSpanBegin, + Optional lifeSpanEnd, + bool isEnded, Optional website, Optional musicBrainzArtistId, + List ipis, + List isnis, + List aliases, + List genres, + List tags, + List ratings, List contributors, List albums, DateTime createdOnUtc, @@ -168,8 +395,25 @@ public sealed class Artist : AggregateRoot id, libraryId, name, + sortName, + disambiguation, + type, + gender, + country, + area, + beginArea, + endArea, + lifeSpanBegin, + lifeSpanEnd, + isEnded, website, musicBrainzArtistId, + ipis, + isnis, + aliases, + genres, + tags, + ratings, contributors, albums, createdOnUtc, @@ -216,14 +460,102 @@ public sealed class Artist : AggregateRoot } /// - /// Updates the details of the artist, without touching the albums and the media contributors. + /// Replaces the aliases of the artist with the provided . + /// + /// The alternative names of the artist. + public void UpdateAliases(IReadOnlyCollection aliases) + { + // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate. + _aliases.Clear(); + _aliases.AddRange(aliases); + } + + /// + /// Replaces the IPI codes of the artist with the provided . + /// + /// The IPI codes of the artist. + public void UpdateIpis(IReadOnlyCollection ipis) + { + // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate. + _ipis.Clear(); + _ipis.AddRange(ipis); + } + + /// + /// Replaces the ISNI codes of the artist with the provided . + /// + /// The ISNI codes of the artist. + public void UpdateIsnis(IReadOnlyCollection isnis) + { + // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate. + _isnis.Clear(); + _isnis.AddRange(isnis); + } + + /// + /// Replaces the genres of the artist with the provided . + /// + /// The genres of the artist. + public void UpdateGenres(IReadOnlyCollection genres) + { + // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate. + _genres.Clear(); + _genres.AddRange(genres); + } + + /// + /// Replaces the tags of the artist with the provided . + /// + /// The tags of the artist. + public void UpdateTags(IReadOnlyCollection tags) + { + // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate. + _tags.Clear(); + _tags.AddRange(tags); + } + + /// + /// Replaces the ratings of the artist with the provided . + /// + /// The ratings of the artist. + public void UpdateRatings(IReadOnlyCollection ratings) + { + // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate. + _ratings.Clear(); + _ratings.AddRange(ratings); + } + + /// + /// Updates the details of the artist, without touching the albums, the contributors, and the media library metadata collections. /// /// The name of the artist. + /// The optional sort name of the artist. + /// The optional disambiguation comment of the artist. + /// The optional type of the artist. + /// The optional gender of the artist. + /// The optional ISO 3166-1 alpha-2 code of the country of the artist. + /// The optional area the artist is primarily identified with. + /// The optional area the artist began in. + /// The optional area the artist ended in. + /// The optional date the artist started existing. + /// The optional date the artist stopped existing. + /// Whether the artist no longer exists. /// The optional website of the artist. /// The optional MusicBrainz identifier of the artist. /// An representing either a successful operation, or an error. public Result UpdateDetails( string name, + Optional sortName, + Optional disambiguation, + Optional type, + Optional gender, + Optional country, + Optional area, + Optional beginArea, + Optional endArea, + Optional lifeSpanBegin, + Optional lifeSpanEnd, + bool isEnded, Optional website, Optional musicBrainzArtistId) { @@ -231,6 +563,17 @@ public sealed class Artist : AggregateRoot return Errors.Music.ArtistNameCannotBeEmpty; Name = name; + SortName = sortName; + Disambiguation = disambiguation; + Type = type; + Gender = gender; + Country = country; + Area = area; + BeginArea = beginArea; + EndArea = endArea; + LifeSpanBegin = lifeSpanBegin; + LifeSpanEnd = lifeSpanEnd; + IsEnded = isEnded; Website = website; MusicBrainzArtistId = musicBrainzArtistId; UpdatedOnUtc = Optional.Some(DateTime.UtcNow); @@ -247,9 +590,14 @@ public sealed class Artist : AggregateRoot /// /// The album to update. /// The album metadata of the album. + /// The optional disambiguation comment of the album. /// The optional physical or digital medium of the album. + /// The optional outermost physical packaging of the album. + /// The optional script used by the language of the release of the album. /// The optional barcode of the album. - /// The optional catalog number of the album. + /// The catalog numbers of the album. + /// The optional name of the label that issued the album. + /// The optional ASIN of the album. /// The optional MusicBrainz identifier of the release. /// The optional MusicBrainz identifier of the release group. /// The optional MusicBrainz identifier of the release artist. @@ -259,9 +607,14 @@ public sealed class Artist : AggregateRoot public Result UpdateAlbum( Album album, AlbumMetadata metadata, + Optional disambiguation, Optional mediaFormat, + Optional packaging, + Optional script, Optional barcode, - Optional catalogNumber, + List catalogNumbers, + Optional label, + Optional asin, Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, @@ -272,7 +625,7 @@ public sealed class Artist : AggregateRoot if (!_albums.Contains(album)) return Errors.Music.AlbumNotFound; - album.UpdateDetails(metadata, mediaFormat, barcode, catalogNumber, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId); + album.UpdateDetails(metadata, disambiguation, mediaFormat, packaging, script, barcode, catalogNumbers, label, asin, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId); album.UpdateContributors(contributors); album.UpdateRatings(ratings); UpdatedOnUtc = Optional.Some(DateTime.UtcNow); @@ -296,10 +649,10 @@ public sealed class Artist : AggregateRoot /// The optional script used by the language of the track. /// The optional musical key of the track. /// The optional tempo of the track in beats per minute. - /// The optional title of the work the track is a recording of. + /// Whether the recording of the track is a video recording. + /// The optional work the track is a recording of. /// The optional MusicBrainz identifier of the recording. /// The optional MusicBrainz identifier of the track. - /// The optional MusicBrainz identifier of the work. /// The moods of the track. /// The ISRCs of the track. /// The media contributors of the track. @@ -315,10 +668,10 @@ public sealed class Artist : AggregateRoot Optional script, Optional key, Optional bpm, - Optional work, + bool isVideo, + Optional work, Optional musicBrainzRecordingId, Optional musicBrainzTrackId, - Optional musicBrainzWorkId, IReadOnlyCollection moods, IReadOnlyCollection isrcs, IReadOnlyCollection contributors, @@ -338,10 +691,10 @@ public sealed class Artist : AggregateRoot script, key, bpm, + isVideo, work, musicBrainzRecordingId, - musicBrainzTrackId, - musicBrainzWorkId); + musicBrainzTrackId); track.UpdateMoods(moods); track.UpdateIsrcs(isrcs); track.UpdateContributors(contributors); diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Album.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Album.cs index 665f7cfd..2ed88cf1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Album.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Album.cs @@ -21,26 +21,52 @@ public sealed class Album : Entity private readonly List _contributors; private readonly List _ratings; private readonly List _tracks; + private readonly List _catalogNumbers; /// /// Gets the album metadata of the album. /// public AlbumMetadata Metadata { get; private set; } + /// + /// Gets the disambiguation comment of the album, used to distinguish albums with the same title, if applicable. + /// + public Optional Disambiguation { get; private set; } + /// /// Gets the physical or digital medium of the album, if applicable. /// public Optional MediaFormat { get; private set; } + /// + /// Gets the outermost physical packaging of the album, if applicable. + /// + public Optional Packaging { get; private set; } + + /// + /// Gets the script used by the language of the release of the album, if applicable. + /// + public Optional Script { get; private set; } + /// /// Gets the barcode of the album, if applicable. /// public Optional Barcode { get; private set; } /// - /// Gets the catalog number of the album, if applicable. + /// Gets the catalog numbers of the album. /// - public Optional CatalogNumber { get; private set; } + public IReadOnlyCollection CatalogNumbers => _catalogNumbers.AsReadOnly(); + + /// + /// Gets the name of the label that issued the album, if applicable. + /// + public Optional Label { get; private set; } + + /// + /// Gets the ASIN (Amazon Standard Identification Number) of the album, if applicable. + /// + public Optional ASIN { get; private set; } /// /// Gets the MusicBrainz identifier of the release, if applicable. @@ -77,9 +103,14 @@ public sealed class Album : Entity /// /// The object representing the unique identifier of the album. /// The album metadata of the album. + /// The optional disambiguation comment of the album. /// The optional physical or digital medium of the album. + /// The optional outermost physical packaging of the album. + /// The optional script used by the language of the release of the album. /// The optional barcode of the album. - /// The optional catalog number of the album. + /// The catalog numbers of the album. + /// The optional name of the label that issued the album. + /// The optional ASIN of the album. /// The optional MusicBrainz identifier of the release. /// The optional MusicBrainz identifier of the release group. /// The optional MusicBrainz identifier of the release artist. @@ -91,9 +122,14 @@ public sealed class Album : Entity private Album( AlbumId id, AlbumMetadata metadata, + Optional disambiguation, Optional mediaFormat, + Optional packaging, + Optional script, Optional barcode, - Optional catalogNumber, + List catalogNumbers, + Optional label, + Optional asin, Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, @@ -105,9 +141,14 @@ public sealed class Album : Entity { Id = id; Metadata = metadata; + Disambiguation = disambiguation; MediaFormat = mediaFormat; + Packaging = packaging; + Script = script; Barcode = barcode; - CatalogNumber = catalogNumber; + _catalogNumbers = catalogNumbers; + Label = label; + ASIN = asin; MusicBrainzReleaseId = musicBrainzReleaseId; MusicBrainzReleaseGroupId = musicBrainzReleaseGroupId; MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId; @@ -122,9 +163,14 @@ public sealed class Album : Entity /// Creates a new instance of the class. /// /// The album metadata of the album. + /// The optional disambiguation comment of the album. /// The optional physical or digital medium of the album. + /// The optional outermost physical packaging of the album. + /// The optional script used by the language of the release of the album. /// The optional barcode of the album. - /// The optional catalog number of the album. + /// The catalog numbers of the album. + /// The optional name of the label that issued the album. + /// The optional ASIN of the album. /// The optional MusicBrainz identifier of the release. /// The optional MusicBrainz identifier of the release group. /// The optional MusicBrainz identifier of the release artist. @@ -136,9 +182,14 @@ public sealed class Album : Entity /// public static Result Create( AlbumMetadata metadata, + Optional disambiguation, Optional mediaFormat, + Optional packaging, + Optional script, Optional barcode, - Optional catalogNumber, + List catalogNumbers, + Optional label, + Optional asin, Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, @@ -149,9 +200,14 @@ public sealed class Album : Entity return new Album( AlbumId.CreateUnique(), metadata, + disambiguation, mediaFormat, + packaging, + script, barcode, - catalogNumber, + catalogNumbers, + label, + asin, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId, @@ -167,9 +223,14 @@ public sealed class Album : Entity /// /// The object representing the unique identifier of the album. /// The album metadata of the album. + /// The optional disambiguation comment of the album. /// The optional physical or digital medium of the album. + /// The optional outermost physical packaging of the album. + /// The optional script used by the language of the release of the album. /// The optional barcode of the album. - /// The optional catalog number of the album. + /// The catalog numbers of the album. + /// The optional name of the label that issued the album. + /// The optional ASIN of the album. /// The optional MusicBrainz identifier of the release. /// The optional MusicBrainz identifier of the release group. /// The optional MusicBrainz identifier of the release artist. @@ -184,9 +245,14 @@ public sealed class Album : Entity public static Result Create( AlbumId id, AlbumMetadata metadata, + Optional disambiguation, Optional mediaFormat, + Optional packaging, + Optional script, Optional barcode, - Optional catalogNumber, + List catalogNumbers, + Optional label, + Optional asin, Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, @@ -199,9 +265,14 @@ public sealed class Album : Entity return new Album( id, metadata, + disambiguation, mediaFormat, + packaging, + script, barcode, - catalogNumber, + catalogNumbers, + label, + asin, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId, @@ -264,26 +335,42 @@ public sealed class Album : Entity /// Updates the details of the album, without touching the ratings, the media contributors, and the tracks. /// /// The album metadata of the album. + /// The optional disambiguation comment of the album. /// The optional physical or digital medium of the album. + /// The optional outermost physical packaging of the album. + /// The optional script used by the language of the release of the album. /// The optional barcode of the album. - /// The optional catalog number of the album. + /// The catalog numbers of the album. + /// The optional name of the label that issued the album. + /// The optional ASIN of the album. /// The optional MusicBrainz identifier of the release. /// The optional MusicBrainz identifier of the release group. /// The optional MusicBrainz identifier of the release artist. /// An representing either a successful operation, or an error. internal Result UpdateDetails( AlbumMetadata metadata, + Optional disambiguation, Optional mediaFormat, + Optional packaging, + Optional script, Optional barcode, - Optional catalogNumber, + List catalogNumbers, + Optional label, + Optional asin, Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId) { Metadata = metadata; + Disambiguation = disambiguation; MediaFormat = mediaFormat; + Packaging = packaging; + Script = script; Barcode = barcode; - CatalogNumber = catalogNumber; + _catalogNumbers.Clear(); + _catalogNumbers.AddRange(catalogNumbers); + Label = label; + ASIN = asin; MusicBrainzReleaseId = musicBrainzReleaseId; MusicBrainzReleaseGroupId = musicBrainzReleaseGroupId; MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId; diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs index d7c418b8..09c42e2c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs @@ -34,6 +34,11 @@ public sealed class Track : Entity /// public AudioMetadata Metadata { get; private set; } + /// + /// Gets the disambiguation comment of the track, used to distinguish tracks with the same title, if applicable. + /// + public Optional Disambiguation { get; private set; } + /// /// Gets the number of the track on its disc. /// @@ -60,9 +65,14 @@ public sealed class Track : Entity public Optional Bpm { get; private set; } /// - /// Gets the title of the work the track is a recording of, if applicable. + /// Gets a value indicating whether the recording of the track is a video recording. /// - public Optional Work { get; private set; } + public bool IsVideo { get; private set; } + + /// + /// Gets the work the track is a recording of, if applicable. + /// + public Optional Work { get; private set; } /// /// Gets the MusicBrainz identifier of the recording, if applicable. @@ -74,11 +84,6 @@ public sealed class Track : Entity /// public Optional MusicBrainzTrackId { get; private set; } - /// - /// Gets the MusicBrainz identifier of the work, if applicable. - /// - public Optional MusicBrainzWorkId { get; private set; } - /// /// Gets the list of moods of the track. /// @@ -105,36 +110,38 @@ public sealed class Track : Entity /// The object representing the unique identifier of the track. /// The file system path of the track. /// The audio metadata of the track. + /// The optional disambiguation comment of the track. /// The number of the track on its disc. /// The optional number of the disc the track belongs to. /// The list of moods of the track. /// The optional script used by the language of the track. /// The optional musical key of the track. /// The optional tempo of the track in beats per minute. + /// Whether the recording of the track is a video recording. /// The list of ISRC of the track. - /// The optional title of the work the track is a recording of. + /// The optional work the track is a recording of. /// The optional MusicBrainz identifier of the recording. /// The optional MusicBrainz identifier of the track. - /// The optional MusicBrainz identifier of the work. /// The list of the media contributors of the track. - /// The list of ratings for the track. + /// The list of ratings of the track. /// The date and time when the entity was created. /// The date and time when the entity was last updated. private Track( TrackId id, string path, AudioMetadata metadata, + Optional disambiguation, int trackNumber, Optional discNumber, List moods, Optional script, Optional key, Optional bpm, + bool isVideo, List isrcs, - Optional work, + Optional work, Optional musicBrainzRecordingId, Optional musicBrainzTrackId, - Optional musicBrainzWorkId, List contributors, List ratings, DateTime createdOnUtc, @@ -143,6 +150,7 @@ public sealed class Track : Entity Id = id; Path = path; Metadata = metadata; + Disambiguation = disambiguation; TrackNumber = trackNumber; DiscNumber = discNumber; _moods = moods; @@ -150,10 +158,10 @@ public sealed class Track : Entity Script = script; Key = key; Bpm = bpm; + IsVideo = isVideo; Work = work; MusicBrainzRecordingId = musicBrainzRecordingId; MusicBrainzTrackId = musicBrainzTrackId; - MusicBrainzWorkId = musicBrainzWorkId; _contributors = contributors; _ratings = ratings; CreatedOnUtc = createdOnUtc; @@ -165,36 +173,38 @@ public sealed class Track : Entity /// /// The file system path of the track. /// The audio metadata of the track. + /// The optional disambiguation comment of the track. /// The number of the track on its disc. /// The optional number of the disc the track belongs to. /// The list of moods of the track. /// The optional script used by the language of the track. /// The optional musical key of the track. /// The optional tempo of the track in beats per minute. + /// Whether the recording of the track is a video recording. /// The list of ISRC of the track. - /// The optional title of the work the track is a recording of. + /// The optional work the track is a recording of. /// The optional MusicBrainz identifier of the recording. /// The optional MusicBrainz identifier of the track. - /// The optional MusicBrainz identifier of the work. /// The list of the media contributors of the track. - /// The list of ratings for the track. + /// The list of ratings of the track. /// /// An containing either a successfully created , or an error message. /// public static Result Create( string path, AudioMetadata metadata, + Optional disambiguation, int trackNumber, Optional discNumber, List moods, Optional script, Optional key, Optional bpm, + bool isVideo, List isrcs, - Optional work, + Optional work, Optional musicBrainzRecordingId, Optional musicBrainzTrackId, - Optional musicBrainzWorkId, List contributors, List ratings) { @@ -202,17 +212,18 @@ public sealed class Track : Entity TrackId.CreateUnique(), path, metadata, + disambiguation, trackNumber, discNumber, moods, script, key, bpm, + isVideo, isrcs, work, musicBrainzRecordingId, musicBrainzTrackId, - musicBrainzWorkId, contributors, ratings, DateTime.UtcNow, // TODO: should be IDateTimeProvider @@ -225,19 +236,20 @@ public sealed class Track : Entity /// The object representing the unique identifier of the track. /// The file system path of the track. /// The audio metadata of the track. + /// The optional disambiguation comment of the track. /// The number of the track on its disc. /// The optional number of the disc the track belongs to. /// The list of moods of the track. /// The optional script used by the language of the track. /// The optional musical key of the track. /// The optional tempo of the track in beats per minute. + /// Whether the recording of the track is a video recording. /// The list of ISRC of the track. - /// The optional title of the work the track is a recording of. + /// The optional work the track is a recording of. /// The optional MusicBrainz identifier of the recording. /// The optional MusicBrainz identifier of the track. - /// The optional MusicBrainz identifier of the work. /// The list of the media contributors of the track. - /// The list of ratings for the track. + /// The list of ratings of the track. /// The date and time when the entity was created. /// The date and time when the entity was last updated. /// @@ -247,17 +259,18 @@ public sealed class Track : Entity TrackId id, string path, AudioMetadata metadata, + Optional disambiguation, int trackNumber, Optional discNumber, List moods, Optional script, Optional key, Optional bpm, + bool isVideo, List isrcs, - Optional work, + Optional work, Optional musicBrainzRecordingId, Optional musicBrainzTrackId, - Optional musicBrainzWorkId, List contributors, List ratings, DateTime createdOnUtc, @@ -267,17 +280,18 @@ public sealed class Track : Entity id, path, metadata, + disambiguation, trackNumber, discNumber, moods, script, key, bpm, + isVideo, isrcs, work, musicBrainzRecordingId, musicBrainzTrackId, - musicBrainzWorkId, contributors, ratings, createdOnUtc, @@ -338,10 +352,10 @@ public sealed class Track : Entity /// The optional script used by the language of the track. /// The optional musical key of the track. /// The optional tempo of the track in beats per minute. - /// The optional title of the work the track is a recording of. + /// Whether the recording of the track is a video recording. + /// The optional work the track is a recording of. /// The optional MusicBrainz identifier of the recording. /// The optional MusicBrainz identifier of the track. - /// The optional MusicBrainz identifier of the work. /// An representing either a successful operation, or an error. internal Result UpdateDetails( string path, @@ -351,10 +365,10 @@ public sealed class Track : Entity Optional script, Optional key, Optional bpm, - Optional work, + bool isVideo, + Optional work, Optional musicBrainzRecordingId, - Optional musicBrainzTrackId, - Optional musicBrainzWorkId) + Optional musicBrainzTrackId) { Path = path; Metadata = metadata; @@ -363,10 +377,10 @@ public sealed class Track : Entity Script = script; Key = key; Bpm = bpm; + IsVideo = isVideo; Work = work; MusicBrainzRecordingId = musicBrainzRecordingId; MusicBrainzTrackId = musicBrainzTrackId; - MusicBrainzWorkId = musicBrainzWorkId; UpdatedOnUtc = Optional.Some(DateTime.UtcNow); return Result.Updated; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs new file mode 100644 index 00000000..58bdb569 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for discovering music file system items. +/// +public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicMetadataExtractionJob.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicMetadataExtractionJob.cs new file mode 100644 index 00000000..3c454483 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicMetadataExtractionJob.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for extracting the metadata of the discovered music file system items, +/// reading it from the embedded tags of the files and falling back to the structure of the media library on disk. +/// +public interface IMusicMetadataExtractionJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalog.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalog.cs new file mode 100644 index 00000000..83cd8493 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalog.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate; + +/// +/// Catalog of the path parts available for music libraries, together with the default structure the application expects on disk. +/// +public sealed class MusicLibraryPathPartCatalog : ILibraryPathPartCatalog +{ + /// + /// Gets the media library type that this catalog supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Music; + + /// + /// Gets the parts that can be used in the path template of a music library. + /// + /// The available path parts. + public IReadOnlyList GetPartDefinitions() + { + return + [ + new(LibraryPathPartKind.Literal, LibraryPathValueType.None, string.Empty, false), + new(LibraryPathPartKind.Separator, LibraryPathValueType.None, string.Empty, false), + new(LibraryPathPartKind.Artist, LibraryPathValueType.Text, "{0}", false), + new(LibraryPathPartKind.ReleaseType, LibraryPathValueType.Enum, "{0}", false), + new(LibraryPathPartKind.ReleaseYear, LibraryPathValueType.Year, "{0}", false), + new(LibraryPathPartKind.ReleaseName, LibraryPathValueType.Text, "{0}", false), + new(LibraryPathPartKind.TrackNumber, LibraryPathValueType.Integer, "{0:00}", false), + new(LibraryPathPartKind.TrackName, LibraryPathValueType.Text, "{0}", false), + new(LibraryPathPartKind.Extension, LibraryPathValueType.Text, "{0}", false), + new(LibraryPathPartKind.DiscNumber, LibraryPathValueType.Integer, "{0:00}", true) + ]; + } + + /// + /// Gets the default path template of a music library, describing the ideal structure the application expects. The disc segment is + /// optional, so that both single disc and multi disc releases are understood. + /// + /// The default path template. + public LibraryPathTemplate GetDefaultTemplate() + { + return LibraryPathTemplate.Create( + [ + LibraryPathPart.Create(LibraryPathPartKind.Artist, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value, + LibraryPathPart.Create(LibraryPathPartKind.ReleaseType, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value, + LibraryPathPart.Create(LibraryPathPartKind.ReleaseYear, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.ReleaseName, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Separator, null, true).Value, + LibraryPathPart.Create(LibraryPathPartKind.Literal, "Disk ", true).Value, + LibraryPathPart.Create(LibraryPathPartKind.DiscNumber, "{0:00}", true).Value, + LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value, + LibraryPathPart.Create(LibraryPathPartKind.TrackNumber, "{0:00}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.TrackName, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Literal, ".", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Extension, "{0}", false).Value + ]); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/IMusicLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/IMusicLibraryTypeScanner.cs new file mode 100644 index 00000000..7dd2cf48 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/IMusicLibraryTypeScanner.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; + +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; + +/// +/// Interface defining a media library scanner for a music media library type. +/// +public interface IMusicLibraryTypeScanner : IMediaTypeScanner +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs new file mode 100644 index 00000000..0965e084 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; + +/// +/// Media library scanner for a music media library type. +/// +internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner +{ + private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory; + + /// + /// The media library type that this media library scanner supports. + /// + public LibraryType SupportedLibraryType { get; } = LibraryType.Music; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating media library scan jobs. + public MusicLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory) + { + _mediaScanJobFactory = mediaScanJobFactory; + } + + /// + /// Creates the media library scan jobs for the provided media library. + /// + /// The unique identifier of the media library for which to create the media library scan jobs. + /// A collection of media library scan jobs. + public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId) + { + // Declare the list of jobs that this scanner requires. + IMusicFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob(libraryId); + IMusicMetadataExtractionJob musicMetadataExtractionJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob(libraryId); + + // Establish the hierarchical relationships between jobs. + fileSystemDiscoveryJob.AddChild(mediaLibraryScanDiffJob); + mediaLibraryScanDiffJob.AddParent(fileSystemDiscoveryJob); + + mediaLibraryScanDiffJob.AddChild(mediaLibraryScanHashJob); + mediaLibraryScanHashJob.AddParent(mediaLibraryScanDiffJob); + + mediaLibraryScanHashJob.AddChild(musicMetadataExtractionJob); + musicMetadataExtractionJob.AddParent(mediaLibraryScanHashJob); + + // The metadata extraction job reads the embedded tags of the discovered music files, falling back to the structure of the media library + // on disk, and stages the extracted metadata, so that the results save job can materialize the artists, albums and tracks from it. + musicMetadataExtractionJob.AddChild(mediaLibraryScanResultsSaveJob); + mediaLibraryScanResultsSaveJob.AddParent(musicMetadataExtractionJob); + + // The enrichment of the media library items is split into independent, modular jobs that run sequentially: the provider configuration + // invalidation job invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, the + // metadata enrichment job enriches the metadata and links the media contributors, and the artwork enrichment job resolves the artwork. + // The artwork enrichment job is always the last job in the directed acyclic job graph, running after the metadata enrichment job. + IMediaLibraryScanProviderConfigurationInvalidationJob mediaLibraryScanProviderConfigurationInvalidationJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanArtworkEnrichmentJob mediaLibraryScanArtworkEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId); + + mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanProviderConfigurationInvalidationJob); + mediaLibraryScanProviderConfigurationInvalidationJob.AddParent(mediaLibraryScanResultsSaveJob); + + mediaLibraryScanProviderConfigurationInvalidationJob.AddChild(mediaLibraryScanMetadataEnrichmentJob); + mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanProviderConfigurationInvalidationJob); + + mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob); + mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob); + + // Return the top level jobs that will be triggered when the scan will be started. + yield return fileSystemDiscoveryJob; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadata.cs index 80ebc675..055e74bc 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadata.cs @@ -14,10 +14,18 @@ namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLib [DebuggerDisplay("{Title}")] public class AlbumMetadata : BaseMetadata { + private readonly List _releaseTypes; + /// - /// Gets the type of the release, if applicable. + /// Gets the title of the specific release (edition) the album files match, if different from the release group title. /// - public Optional ReleaseType { get; } + public Optional ReleaseTitle { get; } + + /// + /// Gets the set of types of the release, if applicable. + /// A MusicBrainz release group can carry more than one type at the same time, for example an album that is also a compilation. + /// + public IReadOnlyCollection ReleaseTypes => _releaseTypes.AsReadOnly(); /// /// Gets the status of the release, if applicable. @@ -39,32 +47,35 @@ public class AlbumMetadata : BaseMetadata /// /// The title of the album. /// The optional original title of the album, if applicable. + /// The optional title of the specific release (edition) of the album. /// The description of the album, if applicable. /// The release information of the album. /// The genres of the album. /// The tags associated with the album. /// The language of the album, if applicable. /// The optional original language of the album, if applicable. - /// The optional type of the release. + /// The set of types of the release, if applicable. /// The optional status of the release. /// The optional number of discs of the release. /// The number of tracks of the release. private AlbumMetadata( string title, Optional originalTitle, + Optional releaseTitle, Optional description, ReleaseInfo releaseInfo, List genres, List tags, Optional language, Optional originalLanguage, - Optional releaseType, + List releaseTypes, Optional releaseStatus, Optional totalDiscs, int totalTracks) : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) { - ReleaseType = releaseType; + ReleaseTitle = releaseTitle; + _releaseTypes = releaseTypes; ReleaseStatus = releaseStatus; TotalDiscs = totalDiscs; TotalTracks = totalTracks; @@ -75,13 +86,14 @@ public class AlbumMetadata : BaseMetadata /// /// The title of the album. /// The optional original title of the album, if applicable. + /// The optional title of the specific release (edition) of the album. /// The description of the album, if applicable. /// The release information of the album. /// The genres of the album. /// The tags associated with the album. /// The language of the album, if applicable. /// The optional original language of the album, if applicable. - /// The optional type of the release. + /// The set of types of the release, if applicable. /// The optional status of the release. /// The optional number of discs of the release. /// The number of tracks of the release. @@ -91,13 +103,14 @@ public class AlbumMetadata : BaseMetadata public static Result Create( string title, Optional originalTitle, + Optional releaseTitle, Optional description, ReleaseInfo releaseInfo, List genres, List tags, Optional language, Optional originalLanguage, - Optional releaseType, + List releaseTypes, Optional releaseStatus, Optional totalDiscs, int totalTracks) @@ -105,13 +118,14 @@ public class AlbumMetadata : BaseMetadata return new AlbumMetadata( title, originalTitle, + releaseTitle, description, releaseInfo, genres, tags, language, originalLanguage, - releaseType, + releaseTypes, releaseStatus, totalDiscs, totalTracks); @@ -125,7 +139,9 @@ public class AlbumMetadata : BaseMetadata { foreach (object component in base.GetEqualityComponents()) yield return component; - yield return ReleaseType; + yield return ReleaseTitle; + foreach (MusicReleaseType releaseType in _releaseTypes) + yield return releaseType; yield return ReleaseStatus; yield return TotalDiscs; yield return TotalTracks; diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArea.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArea.cs new file mode 100644 index 00000000..d4c2ead0 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArea.cs @@ -0,0 +1,111 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Value Object for a MusicBrainz area, the geographic area a music artist is associated with. +/// +[DebuggerDisplay("{Name}")] +public sealed class MusicArea : ValueObject +{ + /// + /// Gets the MusicBrainz identifier of the area. + /// + public MusicBrainzId MusicBrainzAreaId { get; } + + /// + /// Gets the name of the area. + /// + public string Name { get; } + + /// + /// Gets the optional sort name of the area. + /// + public Optional SortName { get; } + + /// + /// Gets the optional disambiguation comment of the area. + /// + public Optional Disambiguation { get; } + + /// + /// Gets the optional MusicBrainz type of the area (e.g., Country, City). + /// + public Optional Type { get; } + + /// + /// Gets the optional ISO 3166 code of the area. + /// + public Optional Iso3166Code { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The MusicBrainz identifier of the area. + /// The name of the area. + /// The optional sort name of the area. + /// The optional disambiguation comment of the area. + /// The optional MusicBrainz type of the area. + /// The optional ISO 3166 code of the area. + private MusicArea( + MusicBrainzId musicBrainzAreaId, + string name, + Optional sortName, + Optional disambiguation, + Optional type, + Optional iso3166Code) + { + MusicBrainzAreaId = musicBrainzAreaId; + Name = name; + SortName = sortName; + Disambiguation = disambiguation; + Type = type; + Iso3166Code = iso3166Code; + } + + /// + /// Creates a new instance of the class. + /// + /// The MusicBrainz identifier of the area. + /// The name of the area. + /// The optional sort name of the area. + /// The optional disambiguation comment of the area. + /// The optional MusicBrainz type of the area. + /// The optional ISO 3166 code of the area. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + MusicBrainzId musicBrainzAreaId, + string name, + Optional sortName, + Optional disambiguation, + Optional type, + Optional iso3166Code) + { + if (string.IsNullOrWhiteSpace(name)) + return Errors.Music.AreaNameCannotBeEmpty; + + return new MusicArea(musicBrainzAreaId, name.Trim(), sortName, disambiguation, type, iso3166Code); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return MusicBrainzAreaId; + yield return Name; + yield return SortName; + yield return Disambiguation; + yield return Type; + yield return Iso3166Code; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAlias.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAlias.cs new file mode 100644 index 00000000..caff08a1 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAlias.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Value Object for an alternative name of a music artist. +/// +[DebuggerDisplay("{Name}")] +public sealed class MusicArtistAlias : ValueObject +{ + /// + /// Gets the name of the alias. + /// + public string Name { get; } + + /// + /// Gets the optional sort name of the alias. + /// + public Optional SortName { get; } + + /// + /// Gets the optional type of the alias (e.g., Artist name, Search hint). + /// + public Optional Type { get; } + + /// + /// Gets the optional locale the alias is used in. + /// + public Optional Locale { get; } + + /// + /// Gets a value indicating whether this is the primary alias of the artist. + /// + public bool IsPrimary { get; } + + /// + /// Gets the optional date the alias began being used. + /// + public Optional BeginDate { get; } + + /// + /// Gets the optional date the alias stopped being used. + /// + public Optional EndDate { get; } + + /// + /// Gets a value indicating whether the alias is no longer used. + /// + public bool IsEnded { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The name of the alias. + /// The optional sort name of the alias. + /// The optional type of the alias. + /// The optional locale the alias is used in. + /// Whether this is the primary alias of the artist. + /// The optional date the alias began being used. + /// The optional date the alias stopped being used. + /// Whether the alias is no longer used. + private MusicArtistAlias( + string name, + Optional sortName, + Optional type, + Optional locale, + bool isPrimary, + Optional beginDate, + Optional endDate, + bool isEnded) + { + Name = name; + SortName = sortName; + Type = type; + Locale = locale; + IsPrimary = isPrimary; + BeginDate = beginDate; + EndDate = endDate; + IsEnded = isEnded; + } + + /// + /// Creates a new instance of the class. + /// + /// The name of the alias. + /// The optional sort name of the alias. + /// The optional type of the alias. + /// The optional locale the alias is used in. + /// Whether this is the primary alias of the artist. + /// The optional date the alias began being used. + /// The optional date the alias stopped being used. + /// Whether the alias is no longer used. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + string name, + Optional sortName, + Optional type, + Optional locale, + bool isPrimary, + Optional beginDate, + Optional endDate, + bool isEnded) + { + if (string.IsNullOrWhiteSpace(name)) + return Errors.Music.ArtistAliasNameCannotBeEmpty; + + return new MusicArtistAlias(name.Trim(), sortName, type, locale, isPrimary, beginDate, endDate, isEnded); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Name; + yield return SortName; + yield return Type; + yield return Locale; + yield return IsPrimary; + yield return BeginDate; + yield return EndDate; + yield return IsEnded; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadata.cs new file mode 100644 index 00000000..0a5a9f8e --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadata.cs @@ -0,0 +1,121 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Value Object for the metadata derived from the file system path of a music library item. +/// +public class MusicLibraryPathMetadata : ValueObject +{ + /// + /// Gets the name of the artist derived from the path, if applicable. + /// + public Optional ArtistName { get; } + + /// + /// Gets the type of the release derived from the path, if applicable. + /// + public Optional ReleaseType { get; } + + /// + /// Gets the release year derived from the path, if applicable. + /// + public Optional ReleaseYear { get; } + + /// + /// Gets the name of the release derived from the path, if applicable. + /// + public Optional ReleaseName { get; } + + /// + /// Gets the number of the track derived from the path, if applicable. + /// + public Optional TrackNumber { get; } + + /// + /// Gets the number of the disc the track belongs to, derived from the path, if applicable. + /// + public Optional DiscNumber { get; } + + /// + /// Gets the title of the track derived from the path, if applicable. + /// + public Optional TrackTitle { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The name of the artist derived from the path, if applicable. + /// The type of the release derived from the path, if applicable. + /// The release year derived from the path, if applicable. + /// The name of the release derived from the path, if applicable. + /// The number of the track derived from the path, if applicable. + /// The number of the disc derived from the path, if applicable. + /// The title of the track derived from the path, if applicable. + private MusicLibraryPathMetadata( + Optional artistName, + Optional releaseType, + Optional releaseYear, + Optional releaseName, + Optional trackNumber, + Optional discNumber, + Optional trackTitle) + { + ArtistName = artistName; + ReleaseType = releaseType; + ReleaseYear = releaseYear; + ReleaseName = releaseName; + TrackNumber = trackNumber; + DiscNumber = discNumber; + TrackTitle = trackTitle; + } + + /// + /// Creates a new instance of the class from the values captured from a path template. + /// + /// The values captured from the path of the music library item. + /// The metadata derived from the captured values. + public static MusicLibraryPathMetadata FromParsedLibraryPath(ParsedLibraryPath parsedPath) + { + Optional releaseType = Optional.None(); + Optional releaseTypeValue = parsedPath.GetString(LibraryPathPartKind.ReleaseType); + if (releaseTypeValue.HasValue) + { + // An unrecognized release type folder does not prevent the rest of the path from being derived, it is simply reported as the catch-all type. + releaseType = Enum.TryParse(releaseTypeValue.Value, ignoreCase: true, out MusicReleaseType parsedReleaseType) + ? Optional.Some(parsedReleaseType) + : Optional.Some(MusicReleaseType.Other); + } + return new MusicLibraryPathMetadata( + parsedPath.GetString(LibraryPathPartKind.Artist), + releaseType, + parsedPath.GetInt(LibraryPathPartKind.ReleaseYear), + parsedPath.GetString(LibraryPathPartKind.ReleaseName), + parsedPath.GetInt(LibraryPathPartKind.TrackNumber), + parsedPath.GetInt(LibraryPathPartKind.DiscNumber), + parsedPath.GetString(LibraryPathPartKind.TrackName)); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return ArtistName; + yield return ReleaseType; + yield return ReleaseYear; + yield return ReleaseName; + yield return TrackNumber; + yield return DiscNumber; + yield return TrackTitle; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWork.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWork.cs new file mode 100644 index 00000000..fc6edc94 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWork.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Value Object for a MusicBrainz work, the musical composition a track is a recording of. +/// +[DebuggerDisplay("{Title}")] +public sealed class MusicWork : ValueObject +{ + private readonly List _languages; + private readonly List _iswcs; + + /// + /// Gets the MusicBrainz identifier of the work. + /// + public MusicBrainzId MusicBrainzWorkId { get; } + + /// + /// Gets the title of the work. + /// + public string Title { get; } + + /// + /// Gets the optional MusicBrainz type of the work (e.g., Song). + /// + public Optional Type { get; } + + /// + /// Gets the list of languages of the work. + /// + public IReadOnlyCollection Languages => _languages.AsReadOnly(); + + /// + /// Gets the list of ISWC (International Standard Musical Work Code) of the work. + /// + public IReadOnlyCollection Iswcs => _iswcs.AsReadOnly(); + + /// + /// Initializes a new instance of the class. + /// + /// The MusicBrainz identifier of the work. + /// The title of the work. + /// The optional MusicBrainz type of the work. + /// The list of languages of the work. + /// The list of ISWC of the work. + private MusicWork( + MusicBrainzId musicBrainzWorkId, + string title, + Optional type, + List languages, + List iswcs) + { + MusicBrainzWorkId = musicBrainzWorkId; + Title = title; + Type = type; + _languages = languages; + _iswcs = iswcs; + } + + /// + /// Creates a new instance of the class. + /// + /// The MusicBrainz identifier of the work. + /// The title of the work. + /// The optional MusicBrainz type of the work. + /// The list of languages of the work. + /// The list of ISWC of the work. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + MusicBrainzId musicBrainzWorkId, + string title, + Optional type, + List languages, + List iswcs) + { + if (string.IsNullOrWhiteSpace(title)) + return Errors.Music.WorkTitleCannotBeEmpty; + + return new MusicWork(musicBrainzWorkId, title.Trim(), type, languages, iswcs); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return MusicBrainzWorkId; + yield return Title; + yield return Type; + foreach (LanguageInfo language in _languages) + yield return language; + foreach (string iswc in _iswcs) + yield return iswc; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs index c4eeea2d..cf805d40 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs @@ -32,7 +32,7 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService /// An representing either a successful operation, or an error. public Result SetDefaultDirectories(string rootPath) { - // make sure the root path exists + // Make sure the root path exists. Result rootPathIdResult = FileSystemPathId.Create(rootPath); if (rootPathIdResult.IsFailure) return rootPathIdResult.Errors; @@ -45,6 +45,10 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService if (createBooksDirectoryResult.IsFailure) return createBooksDirectoryResult.Errors; + Result createMusicDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "music"); + if (createMusicDirectoryResult.IsFailure) + return createMusicDirectoryResult.Errors; + return Result.Created; } @@ -68,7 +72,7 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService if (directoryExistsResult.IsFailure) return directoryExistsResult.Errors; - // only create it if it doesn't already exist + // Only create it if it doesn't already exist. if (!directoryExistsResult.Value) { Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathId, directoryName); diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs index 03c35de9..b6f3fd9f 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs @@ -54,22 +54,22 @@ public class FileTypeService : IFileTypeService /// An containing the type of image or an error. public async Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken) { - // check if the user has access permissions to the provided path + // Check if the user has access permissions to the provided path. if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) return Errors.Permission.UnauthorizedAccess; Memory buffer = new byte[BUFFER_SIZE]; using FileSystemStream stream = _fileSystem.FileStream.New(path.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); - // check if the file's length is less than the buffer size + // Check if the file's length is less than the buffer size. if (stream.Length < BUFFER_SIZE) return ImageType.None; - // read only the first bytes of the file, equal to the buffer size + // Read only the first bytes of the file, equal to the buffer size. await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); byte[] firstBytes = buffer[..BUFFER_SIZE].ToArray(); - // check if its a known image type, based on header bytes + // Check if its a known image type, based on header bytes. ImageType type = IdentifyHeader(firstBytes); if (type != ImageType.None) return type; - // no known image header types were found, check other methods + // No known image header types were found, check other methods. string content = Encoding.UTF8.GetString(buffer.ToArray()); if (IsSvg(content, path.Path)) return ImageType.SVG; @@ -87,20 +87,20 @@ public class FileTypeService : IFileTypeService /// if the file is a SVG image, otherwise. private bool IsSvg(string initialContent, string path) { - // check if it starts with An containing the path segments of the path up one level from , or an error. Result> GoUpOneLevel(string path); + /// + /// Gets the name of the file or directory stored at , using the path separator of the current platform. + /// + /// The path whose name is retrieved. + /// The name of the file or directory stored at . + string GetFileName(string path); + + /// + /// Gets the name of the file stored at without its extension, using the path separator of the current platform. + /// + /// The path whose file name is retrieved. + /// The name of the file stored at without its extension. + string GetFileNameWithoutExtension(string path); + /// /// Returns a collection of characters that are invalid for paths. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs index 18f0d79b..c2e5929a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs @@ -105,6 +105,32 @@ public class PathService : IPathService return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value); } + /// + /// Gets the name of the file or directory stored at , using the path separator of the current platform. + /// + /// The path whose name is retrieved. + /// The name of the file or directory stored at . + public string GetFileName(string path) + { + if (string.IsNullOrEmpty(path)) + return path; + string trimmedPath = path.TrimEnd(PathSeparator); + int lastSeparatorIndex = trimmedPath.LastIndexOf(PathSeparator); + return lastSeparatorIndex < 0 ? trimmedPath : trimmedPath[(lastSeparatorIndex + 1)..]; + } + + /// + /// Gets the name of the file stored at without its extension, using the path separator of the current platform. + /// + /// The path whose file name is retrieved. + /// The name of the file stored at without its extension. + public string GetFileNameWithoutExtension(string path) + { + string fileName = GetFileName(path); + int lastDotIndex = fileName.LastIndexOf('.'); + return lastDotIndex <= 0 ? fileName : fileName[..lastDotIndex]; + } + /// /// Returns a collection of characters that are invalid for paths. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index 91d8ee8f..546bfde3 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -76,6 +76,12 @@ public class Library : AggregateRoot /// public bool ShouldSkipUnchangedDirectoriesDuringScan { get; private set; } + /// + /// Gets the template describing the structure of the media library on disk, always populated with the effective template: the one specified by the + /// user, or the ideal structure of the library type when none was provided. + /// + public LibraryPathTemplate PathTemplate { get; private set; } + /// /// Gets the list of objects representing the file system paths that make up the media library. /// @@ -100,6 +106,7 @@ public class Library : AggregateRoot /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. + /// The template describing the structure of the media library on disk. /// The list of objects representing the unique identifier of scans of the media library. private Library( LibraryId id, @@ -113,6 +120,7 @@ public class Library : AggregateRoot bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, + LibraryPathTemplate pathTemplate, List scanIds) : base(id) { UserId = userId; @@ -125,6 +133,7 @@ public class Library : AggregateRoot CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb; ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories; ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan; + PathTemplate = pathTemplate; _scanIds = scanIds; } @@ -141,6 +150,7 @@ public class Library : AggregateRoot /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. + /// The template describing the structure of the media library on disk. /// The list of objects representing the unique identifier of scans of the media library. /// /// An containing either a successfully created , or an error message. @@ -156,6 +166,7 @@ public class Library : AggregateRoot bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, + LibraryPathTemplate pathTemplate, List scanIds) { List tempContentLocations = []; @@ -179,6 +190,7 @@ public class Library : AggregateRoot canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, + pathTemplate, scanIds ); } @@ -197,6 +209,7 @@ public class Library : AggregateRoot /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. + /// The template describing the structure of the media library on disk. /// The list of objects representing the unique identifier of scans of the media library. /// /// An containing either a successfully created , or an error message. @@ -213,6 +226,7 @@ public class Library : AggregateRoot bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, + LibraryPathTemplate pathTemplate, List scanIds) { List tempContentLocations = []; @@ -236,6 +250,7 @@ public class Library : AggregateRoot canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, + pathTemplate, scanIds ); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPart.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPart.cs new file mode 100644 index 00000000..7ba12252 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPart.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Value Object for one part of a media library path template. +/// +/// +/// A part is either a , which renders the platform path separator, a , which renders its +/// verbatim, or a typed value part, whose is a mask that contains a single {0} placeholder where the captured value goes, +/// optionally with a fixed digit width for numeric kinds, like {0:00}. +/// +public class LibraryPathPart : ValueObject +{ + /// + /// Matches the value placeholder of a typed part, capturing the optional fixed digit width. + /// + private static readonly Regex s_placeholderRegex = new(@"\{0(?::(?0+))?\}", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// + /// Gets the kind of the path part. + /// + public LibraryPathPartKind Kind { get; } + + /// + /// Gets the representation of the path part, which is the literal text for a literal part, and the value mask for a typed part. + /// + public string Representation { get; } + + /// + /// Gets whether the path part can be absent from the path. + /// + public bool IsOptional { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The kind of the path part. + /// The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + private LibraryPathPart(LibraryPathPartKind kind, string representation, bool isOptional) + { + Kind = kind; + Representation = representation; + IsOptional = isOptional; + } + + /// + /// Creates a new instance of the class. + /// + /// The kind of the path part. + /// The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(LibraryPathPartKind kind, string? representation, bool isOptional) + { + // a separator carries no representation, it always renders the platform path separator. + if (kind == LibraryPathPartKind.Separator) + return new LibraryPathPart(kind, string.Empty, isOptional); + + if (string.IsNullOrWhiteSpace(representation)) + return DomainErrors.Library.PathTemplateLiteralCannotBeEmpty; + + // typed parts must carry exactly one value placeholder, so that the position of the captured value is unambiguous. + if (kind != LibraryPathPartKind.Literal && s_placeholderRegex.Matches(representation).Count != 1) + return DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder; + + return new LibraryPathPart(kind, representation, isOptional); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Kind; + yield return Representation; + yield return IsOptional; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplate.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplate.cs new file mode 100644 index 00000000..9288f758 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplate.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Value Object for the ordered sequence of parts that make up the structure of a media library on disk. +/// +public class LibraryPathTemplate : ValueObject +{ + private readonly List _parts; + + /// + /// Gets the ordered parts that make up the path template. + /// + public IReadOnlyList Parts => _parts.AsReadOnly(); + + /// + /// Gets whether the template carries no parts, which means no path derived metadata can be obtained from it. + /// + public bool IsEmpty => _parts.Count == 0; + + /// + /// Initializes a new instance of the class. + /// + /// The ordered parts that make up the path template. + private LibraryPathTemplate(List parts) + { + _parts = parts; + } + + /// + /// Creates a new instance of the class. + /// + /// The ordered parts that make up the path template. + /// The created path template. + public static LibraryPathTemplate Create(IEnumerable parts) + { + return new LibraryPathTemplate([.. parts]); + } + + /// + /// Creates an empty path template, used by the library types that have no path part catalog yet. + /// + /// The created empty path template. + public static LibraryPathTemplate Empty() + { + return new LibraryPathTemplate([]); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + return _parts; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathPartCatalog.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathPartCatalog.cs new file mode 100644 index 00000000..83233fde --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathPartCatalog.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; + +/// +/// Interface for the catalog of the path parts available for a given media library type. +/// +public interface ILibraryPathPartCatalog +{ + /// + /// Gets the media library type that this catalog supports. + /// + LibraryType SupportedLibraryType { get; } + + /// + /// Gets the parts that can be used in the path template of the supported library type. + /// + /// The available path parts. + IReadOnlyList GetPartDefinitions(); + + /// + /// Gets the default path template of the supported library type, describing the ideal structure the application expects. + /// + /// The default path template. + LibraryPathTemplate GetDefaultTemplate(); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathTemplateService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathTemplateService.cs new file mode 100644 index 00000000..b622f6a2 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathTemplateService.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; + +/// +/// Interface for the service that validates media library path templates and derives metadata from paths using them. +/// +public interface ILibraryPathTemplateService +{ + /// + /// Gets the default path template of the provided , or an empty template when the type has no path part catalog yet. + /// + /// The media library type whose default path template is retrieved. + /// The default path template. + LibraryPathTemplate GetDefaultTemplate(LibraryType libraryType); + + /// + /// Resolves the effective path template of a media library of the provided : the template built from the provided + /// , or the ideal structure of the library type when no parts are provided. + /// + /// The media library type the template belongs to. + /// The parts provided by the user. An empty collection means no template was provided, so the library type default is used. + /// + /// An containing either the resolved path template, or an error. + /// + Result ResolveTemplate(LibraryType libraryType, IReadOnlyList providedParts); + + /// + /// Validates the provided against the catalog of the provided . + /// + /// The media library type the template belongs to. + /// The path template to validate. + /// An representing either a successful operation, or an error. + Result Validate(LibraryType libraryType, LibraryPathTemplate template); + + /// + /// Derives the metadata of a media library item from its relative path, using the provided . + /// + /// The media library type the template belongs to. + /// The path template used to parse the path. + /// The path of the media library item, relative to the root of its content location. + /// The character used to separate path segments on the current platform. + /// + /// An containing either the derived metadata, or an error. A successful result whose value has no value + /// means the path does not match the template. + /// + Result> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs new file mode 100644 index 00000000..2f412cb4 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs @@ -0,0 +1,234 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; + +/// +/// Validates media library path templates and derives metadata from paths using them. +/// +public sealed class LibraryPathTemplateService : ILibraryPathTemplateService +{ + /// + /// Matches the value placeholder of a typed part, capturing the optional fixed digit width. + /// + private static readonly Regex s_placeholderRegex = new(@"\{0(?::(?0+))?\}", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private readonly IReadOnlyList _catalogs; + private readonly ConcurrentDictionary _compiledPatterns = new(); + + /// + /// Initializes a new instance of the class. + /// + /// The path part catalogs of all the supported media library types. + public LibraryPathTemplateService(IEnumerable catalogs) + { + _catalogs = [.. catalogs]; + } + + /// + /// Gets the default path template of the provided , or an empty template when the type has no path part catalog yet. + /// + /// The media library type whose default path template is retrieved. + /// The default path template. + public LibraryPathTemplate GetDefaultTemplate(LibraryType libraryType) + { + return ResolveCatalog(libraryType)?.GetDefaultTemplate() ?? LibraryPathTemplate.Empty(); + } + + /// + /// Resolves the effective path template of a media library of the provided : the template built from the provided + /// , or the ideal structure of the library type when no parts are provided. + /// + /// The media library type the template belongs to. + /// The parts provided by the user. An empty collection means no template was provided, so the library type default is used. + /// + /// An containing either the resolved path template, or an error. + /// + public Result ResolveTemplate(LibraryType libraryType, IReadOnlyList providedParts) + { + // An empty set of parts means the user did not provide a template, so the ideal structure of the library type is used. + LibraryPathTemplate template = providedParts.Count == 0 + ? GetDefaultTemplate(libraryType) + : LibraryPathTemplate.Create(providedParts); + Result validationResult = Validate(libraryType, template); + if (validationResult.IsFailure) + return validationResult.Errors; + return template; + } + + /// + /// Validates the provided against the catalog of the provided . + /// + /// The media library type the template belongs to. + /// The path template to validate. + /// An representing either a successful operation, or an error. + public Result Validate(LibraryType libraryType, LibraryPathTemplate template) + { + if (template.IsEmpty) + return Result.Success; + + ILibraryPathPartCatalog? catalog = ResolveCatalog(libraryType); + if (catalog is null) + return DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType; + + HashSet supportedKinds = [.. catalog.GetPartDefinitions().Select(definition => definition.Kind)]; + foreach (LibraryPathPart part in template.Parts) + if (!supportedKinds.Contains(part.Kind)) + return DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType; + return Result.Success; + } + + /// + /// Derives the metadata of a media library item from its relative path, using the provided . + /// + /// The media library type the template belongs to. + /// The path template used to parse the path. + /// The path of the media library item, relative to the root of its content location. + /// The character used to separate path segments on the current platform. + /// + /// An containing either the derived metadata, or an error. A successful result whose value has no value + /// means the path does not match the template. + /// + public Result> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator) + { + if (string.IsNullOrWhiteSpace(relativePath) || template.IsEmpty) + return Result>.Success(Optional.None()); + + Result validationResult = Validate(libraryType, template); + if (validationResult.IsFailure) + return validationResult.Errors; + + ILibraryPathPartCatalog catalog = ResolveCatalog(libraryType)!; + Dictionary definitions = catalog.GetPartDefinitions() + .ToDictionary(definition => definition.Kind); + Regex pattern = GetCompiledPattern(template, definitions, pathSeparator); + Match match = pattern.Match(relativePath); + if (!match.Success) + return Result>.Success(Optional.None()); + + Dictionary values = []; + foreach (LibraryPathPart part in template.Parts) + { + if (part.Kind == LibraryPathPartKind.Literal || part.Kind == LibraryPathPartKind.Separator) + continue; + // A kind can legitimately appear more than once, like the title and the author appearing both in the directory and in the file name, + // so the first non-empty capture is kept. + if (values.ContainsKey(part.Kind)) + continue; + Group group = match.Groups[part.Kind.ToString()]; + if (!group.Success) + continue; + string? value = group.Captures.Cast().Select(capture => capture.Value).FirstOrDefault(captured => !string.IsNullOrWhiteSpace(captured)); + if (!string.IsNullOrWhiteSpace(value)) + values[part.Kind] = value; + } + return Result>.Success(Optional.Some(ParsedLibraryPath.Create(values))); + } + + /// + /// Resolves the catalog of the provided . + /// + /// The media library type whose catalog is resolved. + /// The resolved catalog, or when the type has no catalog. + private ILibraryPathPartCatalog? ResolveCatalog(LibraryType libraryType) + { + return _catalogs.FirstOrDefault(catalog => catalog.SupportedLibraryType == libraryType); + } + + /// + /// Gets the compiled regular expression that matches the provided , building and compiling it only once per distinct + /// pattern, so that scanning a library does not pay the cost of compiling the same pattern once per file. + /// + /// The path template to compile. + /// The available part definitions of the template's library type. + /// The character used to separate path segments on the current platform. + /// The compiled regular expression. + private Regex GetCompiledPattern(LibraryPathTemplate template, IReadOnlyDictionary definitions, char pathSeparator) + { + string patternText = BuildPattern(template, definitions, pathSeparator); + return _compiledPatterns.GetOrAdd(patternText, pattern => new Regex(pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant)); + } + + /// + /// Builds the regular expression text that matches the provided . + /// + /// The path template to compile. + /// The available part definitions of the template's library type. + /// The character used to separate path segments on the current platform. + /// The regular expression text. + private static string BuildPattern(LibraryPathTemplate template, IReadOnlyDictionary definitions, char pathSeparator) + { + StringBuilder patternBuilder = new("^"); + int index = 0; + while (index < template.Parts.Count) + { + int runStart = index; + bool isOptionalRun = template.Parts[index].IsOptional; + do + { + index++; + } + while (index < template.Parts.Count && template.Parts[index].IsOptional == isOptionalRun); + + StringBuilder runBuilder = new(); + for (int runIndex = runStart; runIndex < index; runIndex++) + runBuilder.Append(BuildFragment(template.Parts[runIndex], definitions, pathSeparator)); + + if (isOptionalRun) + patternBuilder.Append("(?:").Append(runBuilder).Append(")?"); + else + patternBuilder.Append(runBuilder); + } + patternBuilder.Append('$'); + return patternBuilder.ToString(); + } + + /// + /// Builds the regular expression fragment of a single path part. + /// + /// The path part to compile. + /// The available part definitions of the template's library type. + /// The character used to separate path segments on the current platform. + /// The compiled regular expression fragment. + private static string BuildFragment(LibraryPathPart part, IReadOnlyDictionary definitions, char pathSeparator) + { + if (part.Kind == LibraryPathPartKind.Separator) + return Regex.Escape(pathSeparator.ToString()); + if (part.Kind == LibraryPathPartKind.Literal) + return Regex.Escape(part.Representation); + + LibraryPathPartDefinition definition = definitions[part.Kind]; + Match placeholder = s_placeholderRegex.Match(part.Representation); + string prefix = part.Representation[..placeholder.Index]; + string suffix = part.Representation[(placeholder.Index + placeholder.Length)..]; + Group width = placeholder.Groups["width"]; + // A fixed width narrows the capture to an exact number of digits, otherwise the base pattern of the value type is used. + string valuePattern = width.Success ? $@"\d{{{width.Value.Length}}}" : GetValuePattern(definition.ValueType); + return Regex.Escape(prefix) + $"(?<{part.Kind}>{valuePattern})" + Regex.Escape(suffix); + } + + /// + /// Gets the base regular expression pattern of the provided . + /// + /// The value type whose base pattern is retrieved. + /// The base regular expression pattern. + private static string GetValuePattern(LibraryPathValueType valueType) + { + return valueType switch + { + LibraryPathValueType.Year => @"\d{4}", + LibraryPathValueType.Integer => @"\d+", + _ => @"[^/\\]+" + }; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs index bb976ead..f75e5d94 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; using Microsoft.Extensions.DependencyInjection; using System; @@ -32,7 +33,7 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory { return libraryType switch { - // implemented scanners + // Implemented scanners. LibraryType.Book => _serviceProvider.GetRequiredService(), LibraryType.EBook => throw new NotImplementedException("EBook scanner is not implemented."), LibraryType.ComicBook => throw new NotImplementedException("ComicBook scanner is not implemented."), @@ -55,7 +56,7 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory LibraryType.InterviewVideo => throw new NotImplementedException("InterviewVideo scanner is not implemented."), LibraryType.CoverSongVideo => throw new NotImplementedException("CoverSongVideo scanner is not implemented."), LibraryType.PodcastVideo => throw new NotImplementedException("PodcastVideo scanner is not implemented."), - LibraryType.Music => throw new NotImplementedException("Music scanner is not implemented."), + LibraryType.Music => _serviceProvider.GetRequiredService(), LibraryType.Audiobook => throw new NotImplementedException("Audiobook scanner is not implemented."), LibraryType.LiveRecordingAudio => throw new NotImplementedException("LiveRecordingAudio scanner is not implemented."), LibraryType.InterviewAudio => throw new NotImplementedException("InterviewAudio scanner is not implemented."), @@ -68,7 +69,7 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory LibraryType.Collection => throw new NotImplementedException("Collection scanner is not implemented."), LibraryType.Subtitles => throw new NotImplementedException("Subtitles scanner is not implemented."), LibraryType.Lyrics => throw new NotImplementedException("Lyrics scanner is not implemented."), - // catch-all for unknown or unsupported types + // Catch-all for unknown or unsupported types. _ => throw new ArgumentOutOfRangeException(nameof(libraryType), $"No scanner exists for library type '{libraryType}'.") }; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinition.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinition.cs new file mode 100644 index 00000000..f3363a59 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinition.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Value Object that describes one available part of a media library path template, for a given library type. +/// +public sealed class LibraryPathPartDefinition : ValueObject +{ + /// + /// Gets the kind of the described part. + /// + public LibraryPathPartKind Kind { get; } + + /// + /// Gets the value type captured by the described part. + /// + public LibraryPathValueType ValueType { get; } + + /// + /// Gets the default representation of the described part, pre-filled for the user when the part is added to a template. + /// + public string DefaultRepresentation { get; } + + /// + /// Gets whether the described part is optional by default. + /// + public bool IsOptionalByDefault { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The kind of the described part. + /// The value type captured by the described part. + /// The default representation of the described part. + /// Whether the described part is optional by default. + public LibraryPathPartDefinition(LibraryPathPartKind kind, LibraryPathValueType valueType, string defaultRepresentation, bool isOptionalByDefault) + { + Kind = kind; + ValueType = valueType; + DefaultRepresentation = defaultRepresentation; + IsOptionalByDefault = isOptionalByDefault; + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Kind; + yield return ValueType; + yield return DefaultRepresentation; + yield return IsOptionalByDefault; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPath.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPath.cs new file mode 100644 index 00000000..a71096c1 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPath.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Value Object for the values captured from the relative path of a media library item, keyed by the semantic kind of the path part that produced them. +/// +public class ParsedLibraryPath : ValueObject +{ + private readonly IReadOnlyDictionary _values; + + /// + /// Gets the captured values, keyed by their part kind. + /// + public IReadOnlyDictionary Values => _values; + + /// + /// Initializes a new instance of the class. + /// + /// The captured values, keyed by their part kind. + private ParsedLibraryPath(IReadOnlyDictionary values) + { + _values = values; + } + + /// + /// Creates a new instance of the class. + /// + /// The captured values, keyed by their part kind. + /// The created parsed path. + public static ParsedLibraryPath Create(IReadOnlyDictionary values) + { + return new ParsedLibraryPath(values); + } + + /// + /// Gets the captured value of the part of the provided . + /// + /// The kind of the part whose value is retrieved. + /// An containing the captured value, or no value when the part was not captured. + public Optional GetString(LibraryPathPartKind kind) + { + return _values.TryGetValue(kind, out string? value) && !string.IsNullOrWhiteSpace(value) + ? Optional.Some(value.Trim()) + : Optional.None(); + } + + /// + /// Gets the captured integer value of the part of the provided . + /// + /// The kind of the part whose value is retrieved. + /// An containing the captured integer, or no value when the part was not captured or is not an integer. + public Optional GetInt(LibraryPathPartKind kind) + { + return _values.TryGetValue(kind, out string? value) && int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) + ? Optional.Some(parsed) + : Optional.None(); + } + + /// + /// Gets the captured values as a dictionary, for callers that need to iterate over all of them. + /// + /// The captured values keyed by part kind. + public IReadOnlyDictionary ToDictionary() + { + return _values.ToDictionary(pair => pair.Key, pair => pair.Value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + // the captured values are stored in a dictionary, so they are ordered by their kind to keep equality independent of insertion order. + foreach (KeyValuePair capturedValue in _values.OrderBy(capturedValue => capturedValue.Key)) + { + yield return capturedValue.Key; + yield return capturedValue.Value; + } + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs index 067f3f0a..59f22083 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs @@ -20,6 +20,7 @@ public class UserSettings : AggregateRoot private const bool DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER = false; private const bool DEFAULT_IS_THEME_CACHING_ENABLED = true; private const bool DEFAULT_AGGREGATE_METADATA_WHEN_MISSING = false; + private const bool DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING = false; private const bool DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES = false; private const bool DEFAULT_SHOULD_PRESERVE_BOOK_STYLES = true; @@ -53,6 +54,11 @@ public class UserSettings : AggregateRoot /// public bool ShouldAggregateMetadataWhenMissing { get; private set; } + /// + /// Gets whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. + /// + public bool ShouldAggregateArtworkWhenMissing { get; private set; } + /// /// Gets whether PDF books are rendered as page images for the user, or not. Rendering PDFs as images preserves the original /// layout, but the pages are not selectable or searchable, unlike their text layer. @@ -76,6 +82,7 @@ public class UserSettings : AggregateRoot /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. private UserSettings( @@ -86,6 +93,7 @@ public class UserSettings : AggregateRoot bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing, + bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, bool shouldPreserveBookStyles) : base(id) { @@ -95,6 +103,7 @@ public class UserSettings : AggregateRoot ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; IsThemeCachingEnabled = isThemeCachingEnabled; ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing; + ShouldAggregateArtworkWhenMissing = shouldAggregateArtworkWhenMissing; ShouldRenderPdfAsImages = shouldRenderPdfAsImages; ShouldPreserveBookStyles = shouldPreserveBookStyles; } @@ -114,6 +123,7 @@ public class UserSettings : AggregateRoot DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, + DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING, DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES, DEFAULT_SHOULD_PRESERVE_BOOK_STYLES ); @@ -135,6 +145,7 @@ public class UserSettings : AggregateRoot DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING, + DEFAULT_AGGREGATE_ARTWORK_WHEN_MISSING, DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES, DEFAULT_SHOULD_PRESERVE_BOOK_STYLES ); @@ -149,6 +160,7 @@ public class UserSettings : AggregateRoot /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. /// @@ -161,6 +173,7 @@ public class UserSettings : AggregateRoot bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing, + bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, bool shouldPreserveBookStyles) { @@ -175,6 +188,7 @@ public class UserSettings : AggregateRoot shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing, + shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, shouldPreserveBookStyles); } @@ -189,6 +203,7 @@ public class UserSettings : AggregateRoot /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. /// @@ -202,13 +217,14 @@ public class UserSettings : AggregateRoot bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing, + bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, bool shouldPreserveBookStyles) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing, shouldRenderPdfAsImages, shouldPreserveBookStyles); + return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing, shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, shouldPreserveBookStyles); } /// @@ -219,6 +235,7 @@ public class UserSettings : AggregateRoot /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. /// Whether PDF books are rendered as page images for the user, or not. /// Whether the styles of the book content are preserved when it is rendered for the user, or not. /// An representing either a successful update, or an error. @@ -228,6 +245,7 @@ public class UserSettings : AggregateRoot bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing, + bool shouldAggregateArtworkWhenMissing, bool shouldRenderPdfAsImages, bool shouldPreserveBookStyles) { @@ -239,6 +257,7 @@ public class UserSettings : AggregateRoot ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; IsThemeCachingEnabled = isThemeCachingEnabled; ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing; + ShouldAggregateArtworkWhenMissing = shouldAggregateArtworkWhenMissing; ShouldRenderPdfAsImages = shouldRenderPdfAsImages; ShouldPreserveBookStyles = shouldPreserveBookStyles; return Result.Updated; diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalog.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalog.cs new file mode 100644 index 00000000..a13e622e --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalog.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate; + +/// +/// Catalog of the path parts available for book libraries, together with the default structure the application expects on disk. +/// +/// +/// The default structure mirrors the Calibre library layout, where each book lives in an author directory and a book directory named after +/// the title and the Calibre identifier, holding the book file named after the title and the author. +/// +public sealed class BookLibraryPathPartCatalog : ILibraryPathPartCatalog +{ + /// + /// Gets the media library type that this catalog supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Gets the parts that can be used in the path template of a book library. + /// + /// The available path parts. + public IReadOnlyList GetPartDefinitions() + { + return + [ + new(LibraryPathPartKind.Literal, LibraryPathValueType.None, string.Empty, false), + new(LibraryPathPartKind.Separator, LibraryPathValueType.None, string.Empty, false), + new(LibraryPathPartKind.Author, LibraryPathValueType.Text, "{0}", false), + new(LibraryPathPartKind.Title, LibraryPathValueType.Text, "{0}", false), + new(LibraryPathPartKind.Series, LibraryPathValueType.Text, "{0}", true), + new(LibraryPathPartKind.SeriesNumber, LibraryPathValueType.Integer, "{0}", true), + new(LibraryPathPartKind.BookId, LibraryPathValueType.Integer, "{0}", false), + new(LibraryPathPartKind.Extension, LibraryPathValueType.Text, "{0}", false) + ]; + } + + /// + /// Gets the default path template of a book library, describing the Calibre structure the application expects. + /// + /// The default path template. + public LibraryPathTemplate GetDefaultTemplate() + { + return LibraryPathTemplate.Create( + [ + LibraryPathPart.Create(LibraryPathPartKind.Author, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Title, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Literal, " (", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.BookId, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Literal, ")", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Separator, null, false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Title, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Author, "{0}", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Literal, ".", false).Value, + LibraryPathPart.Create(LibraryPathPartKind.Extension, "{0}", false).Value + ]); + } +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 7e857371..10e7c307 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -12,27 +12,32 @@ using Lumina.Application.Common.Infrastructure.Scheduling; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using Lumina.Infrastructure.Common.DomainEvents; using Lumina.Infrastructure.Common.Models.DTO.Plugins; +using Lumina.Infrastructure.Common.Networking; using Lumina.Infrastructure.Core.Authentication; using Lumina.Infrastructure.Core.Authorization; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership; using Lumina.Infrastructure.Core.Authorization.Policies.Over18; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Infrastructure.Core.Plugins; @@ -51,6 +56,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; +using System.Net.Http; using System.Reflection; #endregion @@ -104,6 +110,8 @@ public static class InfrastructureLayerServices services.AddHostedService(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -111,13 +119,33 @@ public static class InfrastructureLayerServices services.AddTransient(); services.AddTransient(); + // The media library type specific behavior of the generic scan jobs is provided by the materializers and the enrichers, selected by the media library type. + // Registering several implementations of the same interface is intentional and does not override anything: the container keeps every registration, + // and the scan jobs resolve them as a collection (GetServices) and pick the one whose SupportedLibraryType matches the scanned library. Resolving a + // single instance of one of these interfaces would instead return only the last registration, so they must always be resolved as a collection. + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddSingleton(); services.AddSingleton(); + // Artwork downloads: the remote artwork of any provider is downloaded through a client that follows redirects only to public HTTPS hosts, + // so a URL returned by a provider, or a redirect it points at, can never reach a private, loopback or link local address of the host. + services.AddHttpClient(NamedHttpClients.ARTWORK_DOWNLOAD) + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }) + .AddHttpMessageHandler(() => new PublicHostRedirectHandler()); + // Book artwork: stores the artwork of the books into the internal media directory. - services.AddHttpClient(); services.AddScoped(); + // Music artwork: stores the artwork of the albums into the internal media directory. + services.AddScoped(); + // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents. // The enablement cache lets the reading service skip the per-request database read of the reader configurations. services.AddSingleton(); @@ -153,6 +181,7 @@ public static class InfrastructureLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index 60244347..d5aa5e0e 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -15,6 +15,7 @@ public static partial class Errors public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty)); public static Error MediaLibrariesDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaLibrariesDirectoryCannotBeEmpty)); public static Error MediaBooksDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaBooksDirectoryCannotBeEmpty)); + public static Error MediaMusicDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaMusicDirectoryCannotBeEmpty)); public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty)); public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String)); public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty)); diff --git a/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs b/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs new file mode 100644 index 00000000..926e983d --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs @@ -0,0 +1,12 @@ +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Names of the named HTTP clients registered by the infrastructure layer. +/// +internal static class NamedHttpClients +{ + /// + /// The name of the HTTP client used to download remote artwork, whose redirects are followed only to public hosts. + /// + internal const string ARTWORK_DOWNLOAD = "artwork-download"; +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs new file mode 100644 index 00000000..a72b0354 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Message handler that validates the host of the initial request, and follows the redirects of the response only to public HTTPS hosts, so that +/// neither the URL emitted by a provider nor a server controlled redirect can make the host issue a request to a private, loopback, link local or +/// otherwise internal address. It is provider agnostic: it protects every download that is routed through the client it is attached to. +/// +internal sealed class PublicHostRedirectHandler : DelegatingHandler +{ + /// + /// The maximum number of redirects that are followed before the request is considered to be looping. + /// + private const int MAXIMUM_REDIRECT_COUNT = 5; + + /// + /// Sends the request, validating that its host is public, and following its redirects only to public HTTPS hosts. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The final response of the request. + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + // The sink is provider agnostic, so the initial request is validated too, not only the redirects, so a provider that emits an internal URL + // cannot make the host fetch a private, loopback or link local address before any redirect is even involved. + Uri? initialUri = request.RequestUri; + string initialHost = initialUri is { IsAbsoluteUri: true } ? initialUri.Host : string.Empty; + if (initialUri is not { IsAbsoluteUri: true } || !PublicHostValidator.IsPublicHost(initialHost)) + throw new HttpRequestException($"The request was sent to the disallowed host '{initialHost}'."); + + HttpRequestMessage currentRequest = request; + // The requests created here to follow a redirect are owned by this handler, so they are disposed once the sending is complete. + List redirectRequests = []; + + try + { + for (int redirectCount = 0; ; redirectCount++) + { + Uri requestUri = currentRequest.RequestUri ?? throw new HttpRequestException("The request has no request URI."); + + HttpResponseMessage response = await base.SendAsync(currentRequest, cancellationToken).ConfigureAwait(false); + + if (!IsRedirect(response.StatusCode) || response.Headers.Location is null) + return response; + + Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location); + // The response of a redirect is not returned, so it must be disposed here to release its connection. + response.Dispose(); + + if (redirectCount >= MAXIMUM_REDIRECT_COUNT) + throw new HttpRequestException("The request was redirected too many times."); + + // Only public HTTPS targets are followed, so a redirect can never reach a private, loopback, link local or other internal address, + // nor downgrade the transfer back to an unencrypted one. + if (redirectUri is null || redirectUri.Scheme != Uri.UriSchemeHttps || !PublicHostValidator.IsPublicHost(redirectUri.Host)) + throw new HttpRequestException($"The request was redirected to the disallowed host '{redirectUri?.Host}'."); + + HttpRequestMessage redirectRequest = CloneRequest(currentRequest, redirectUri); + redirectRequests.Add(redirectRequest); + currentRequest = redirectRequest; + } + } + finally + { + foreach (HttpRequestMessage redirectRequest in redirectRequests) + redirectRequest.Dispose(); + } + } + + /// + /// Determines whether the provided status code is a redirect. + /// + /// The status code to check. + /// when the status code is a redirect, otherwise . + private static bool IsRedirect(HttpStatusCode statusCode) + { + return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect; + } + + /// + /// Resolves the location of a redirect against the URI of the request it was returned for. + /// + /// The URI of the request the redirect was returned for. + /// The location of the redirect. + /// The absolute URI of the redirect, or when it could not be resolved. + private static Uri? ResolveRedirect(Uri requestUri, Uri location) + { + if (location.IsAbsoluteUri) + return location; + return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null; + } + + /// + /// Creates the request used to follow a redirect to , carrying over the method and the headers of + /// . It is meant for the bodyless GET downloads this handler is registered for. + /// + /// The request that is being redirected. + /// The URI of the redirect target. + /// The request used to follow the redirect. + private static HttpRequestMessage CloneRequest(HttpRequestMessage request, Uri requestUri) + { + HttpRequestMessage redirectRequest = new(request.Method, requestUri) + { + Version = request.Version, + VersionPolicy = request.VersionPolicy + }; + foreach (KeyValuePair> header in request.Headers) + redirectRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); + return redirectRequest; + } +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs new file mode 100644 index 00000000..4f0ce059 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Net; +using System.Net.Sockets; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Determines whether a host is public, so that a request can never be sent to a private, loopback, link local or otherwise internal address. +/// +internal static class PublicHostValidator +{ + /// + /// Determines whether the provided host is a public host. + /// + /// The host to check. + /// when the host is public, otherwise . + /// + /// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. An IP literal is accepted + /// only when it is a public address, so the unspecified, private, loopback, link local and carrier grade NAT ranges are all rejected. + /// + public static bool IsPublicHost(string host) + { + if (string.IsNullOrWhiteSpace(host)) + return false; + + // Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept. + string normalizedHost = host.Trim('[', ']'); + if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase)) + return false; + + if (!IPAddress.TryParse(normalizedHost, out IPAddress? address)) + return true; + + if (address.IsIPv4MappedToIPv6) + address = address.MapToIPv4(); + + if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) + return false; + + if (address.AddressFamily == AddressFamily.InterNetwork) + { + byte[] octets = address.GetAddressBytes(); + return octets[0] switch + { + 0 => false, + 10 => false, + 100 when octets[1] is >= 64 and <= 127 => false, + 127 => false, + 169 when octets[1] == 254 => false, + 172 when octets[1] is >= 16 and <= 31 => false, + 192 when octets[1] == 168 => false, + _ => true + }; + } + + if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal) + return false; + + byte[] addressBytes = address.GetAddressBytes(); + // The fc00::/7 unique local range is rejected, matching the private IPv4 ranges. + if ((addressBytes[0] & 0xFE) == 0xFC) + return false; + + return true; + } +} diff --git a/src/Lumina.Infrastructure/Common/Utilities/ImageTypeUtilities.cs b/src/Lumina.Infrastructure/Common/Utilities/ImageTypeUtilities.cs new file mode 100644 index 00000000..5916b6c4 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Utilities/ImageTypeUtilities.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +#endregion + +namespace Lumina.Infrastructure.Common.Utilities; + +/// +/// Provides helpers for the enumeration. +/// +public static class ImageTypeUtilities +{ + /// + /// Gets the conventional file extension of the provided , without the leading dot. + /// + /// The image type whose file extension is resolved. + /// The file extension of the image type, or bin when the type is not a recognized image. + public static string ToFileExtension(this ImageType imageType) + { + return imageType switch + { + ImageType.BMP => "bmp", + ImageType.GIF => "gif", + ImageType.PNG => "png", + ImageType.TIFF => "tiff", + ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG_UNKNOWN => "jpg", + ImageType.PICT => "pct", + ImageType.ICO => "ico", + ImageType.PSD => "psd", + ImageType.JPEG2000 => "jp2", + ImageType.AVIF => "avif", + ImageType.WEBP => "webp", + ImageType.TGA => "tga", + ImageType.SVG => "svg", + _ => "bin" + }; + } +} diff --git a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs index 3c3b9829..d5eb92a9 100644 --- a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs @@ -27,5 +27,9 @@ public class MediaSettingsDtoValidator : AbstractValidator RuleFor(settings => settings.BooksDirectory) .NotEmpty() .WithError(Errors.Errors.Configuration.MediaBooksDirectoryCannotBeEmpty); + + RuleFor(settings => settings.MusicDirectory) + .NotEmpty() + .WithError(Errors.Errors.Configuration.MediaMusicDirectoryCannotBeEmpty); } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs new file mode 100644 index 00000000..28ccb723 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs @@ -0,0 +1,457 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Common.Utilities; +using Lumina.Infrastructure.Common.Networking; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Stores the artwork of an album into the internal media directory, under a per-album directory, and returns its relative path. +/// +internal sealed class MusicArtworkService : IMusicArtworkService +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _environmentContext; + private readonly IPathService _pathService; + private readonly IHttpClientFactory _httpClientFactory; + private readonly MediaSettingsDto _mediaSettings; + + /// + /// Initializes a new instance of the class. + /// + /// Injected facade service for environment contextual services. + /// Injected service for handling file system paths. + /// Injected factory used to create the HTTP clients that download the remote artwork. + /// Injected service for retrieving . + public MusicArtworkService(IEnvironmentContext environmentContext, IPathService pathService, IHttpClientFactory httpClientFactory, IOptions mediaSettingsOptions) + { + _environmentContext = environmentContext; + _pathService = pathService; + _httpClientFactory = httpClientFactory; + _mediaSettings = mediaSettingsOptions.Value; + } + + /// + /// Stores the of the album into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null) + { + Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false); + } + + /// + /// Stores the of the artist into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken) + { + Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the local source of the , stores it into , and cleans up the temporary download of a remote artwork. + /// + /// The file system path of the directory the artwork is stored into. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + private async Task> SaveArtworkAsync(string artworkDirectoryPath, ArtworkDto artwork, CancellationToken cancellationToken) + { + // Resolve the local file path of the artwork, downloading it to a temporary file when it is remote. + Result resolveSourceResult = await ResolveArtworkSourceAsync(artwork, cancellationToken).ConfigureAwait(false); + if (resolveSourceResult.IsFailure) + return resolveSourceResult.Errors; + string sourcePath = resolveSourceResult.Value.Path; + + try + { + return await StoreArtworkAsync(artworkDirectoryPath, artwork.Type, artwork.Ordinal, sourcePath, cancellationToken).ConfigureAwait(false); + } + finally + { + // Remove the temporary source of the artwork, whether it was downloaded for a remote artwork or produced by a provider, never a file of the user. + if (resolveSourceResult.Value.IsTemporary && File.Exists(sourcePath)) + { + try + { + File.Delete(sourcePath); + } + 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. + } + } + } + } + + /// + /// Deletes the stored artwork of the album from the internal media directory. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. + /// An representing either a successful operation, or an error. + public Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null) + { + Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value); + } + + /// + /// Deletes the stored artwork of the artist from the internal media directory. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// An representing either a successful operation, or an error. + public Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName) + { + Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value); + } + + /// + /// Deletes the files directly contained in , leaving the subdirectories, such as the album directories of an artist, untouched. + /// + /// The file system path of the directory whose files are deleted. + /// An representing either a successful operation, or an error. + private Result DeleteArtworkInDirectory(string artworkDirectoryPath) + { + Result directoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath); + if (directoryPathIdResult.IsFailure) + return directoryPathIdResult.Errors; + + // When nothing was stored for the owner yet, its directory does not exist, so there is nothing to delete. + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + return directoryExistsResult.Errors; + if (!directoryExistsResult.Value) + return Result.Deleted; + + Result> getFilesResult = _environmentContext.FileProviderService.GetFilePaths(directoryPathIdResult.Value, true); + if (getFilesResult.IsFailure) + return getFilesResult.Errors; + + foreach (FileSystemPathId filePathId in getFilesResult.Value) + _environmentContext.FileProviderService.DeleteFile(filePathId); + + return Result.Deleted; + } + + /// + /// Stores the artwork file at into . + /// + /// The file system path of the directory the artwork is stored into. + /// The type of the artwork being stored. + /// The ordinal of the artwork within its type. + /// The file system path of the artwork file to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + private async Task> StoreArtworkAsync(string artworkDirectoryPath, ArtworkType artworkType, int ordinal, string sourcePath, CancellationToken cancellationToken) + { + Result sourcePathIdResult = FileSystemPathId.Create(sourcePath); + if (sourcePathIdResult.IsFailure) + return sourcePathIdResult.Errors; + + Result fileExistsResult = _environmentContext.FileProviderService.FileExists(sourcePathIdResult.Value); + if (fileExistsResult.IsFailure) + return fileExistsResult.Errors; + if (!fileExistsResult.Value) + return Errors.FileSystemManagement.FileNotFound; + + // Reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine. + if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.ReparsePoint)) + return Errors.FileSystemManagement.InvalidPath; + + // Reject the artwork when it exceeds the maximum allowed size. + FileInfo sourceFileInfo = new(sourcePath); + if (sourceFileInfo.Length > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + + // Make sure the file is an actual supported image. + Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(sourcePathIdResult.Value, cancellationToken).ConfigureAwait(false); + if (imageTypeResult.IsFailure) + return imageTypeResult.Errors; + if (imageTypeResult.Value == ImageType.None) + return Errors.Library.CoverFileMustBeAnImage; + + Result ensureDirectoryResult = EnsureDirectory(artworkDirectoryPath); + if (ensureDirectoryResult.IsFailure) + return ensureDirectoryResult.Errors; + + Result artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath); + if (artworkDirectoryPathIdResult.IsFailure) + return artworkDirectoryPathIdResult.Errors; + + // Copy the artwork file from the source location. + Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourcePathIdResult.Value, artworkDirectoryPathIdResult.Value, true); + if (copyFileResult.IsFailure) + return copyFileResult.Errors; + + // Rename the copied file to the standard naming, derived from the type and the ordinal of the artwork. + Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"{BuildArtworkFileStem(artworkType, ordinal)}.{imageTypeResult.Value.ToFileExtension()}"); + if (renameFileResult.IsFailure) + return renameFileResult.Errors; + + // Get the internal relative path for the copied file. + string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..]; + if (!relativePath.StartsWith(_pathService.PathSeparator)) + relativePath = $"{_pathService.PathSeparator}{relativePath}"; + return relativePath; + } + + /// + /// Builds the file name stem of an artwork, derived from its type and ordinal. + /// + /// The type of the artwork. + /// The ordinal of the artwork within its type. + /// The file name stem of the artwork. + private static string BuildArtworkFileStem(ArtworkType artworkType, int ordinal) + { + string stem = artworkType switch + { + ArtworkType.Cover => "cover", + ArtworkType.Front => "front", + ArtworkType.Back => "back", + ArtworkType.Booklet => "booklet", + ArtworkType.Medium => "medium", + ArtworkType.Tray => "tray", + ArtworkType.Spine => "spine", + ArtworkType.Obi => "obi", + ArtworkType.Sticker => "sticker", + ArtworkType.Poster => "poster", + ArtworkType.Liner => "liner", + ArtworkType.Watermark => "watermark", + ArtworkType.Backdrop => "backdrop", + ArtworkType.Banner => "banner", + ArtworkType.Logo => "logo", + ArtworkType.Thumb => "thumb", + _ => "other" + }; + return ordinal > 0 ? $"{stem}-{ordinal}" : stem; + } + + /// + /// Resolves the local file system path of the , downloading it to a temporary file when it is remote. + /// + /// The artwork whose source path is resolved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the resolved local source of the artwork, or an error. + private async Task> ResolveArtworkSourceAsync(ArtworkDto artwork, CancellationToken cancellationToken) + { + if (!string.IsNullOrWhiteSpace(artwork.LocalPath)) + return new ArtworkSourceResult(artwork.LocalPath, IsTemporary: artwork.IsTemporary); + + if (string.IsNullOrWhiteSpace(artwork.RemoteUrl)) + return Errors.FileSystemManagement.FileNotFound; + + // Download the remote artwork into a temporary file, aborting when it exceeds the allowed size. + using HttpClient httpClient = _httpClientFactory.CreateClient(NamedHttpClients.ARTWORK_DOWNLOAD); + string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}"); + bool downloaded = false; + try + { + using HttpResponseMessage response = await httpClient.GetAsync(artwork.RemoteUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + return Errors.FileSystemManagement.FileNotFound; + + await using Stream responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using FileStream fileStream = new(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true); + + byte[] buffer = new byte[81920]; + long totalRead = 0; + int bytesRead; + while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + totalRead += bytesRead; + if (totalRead > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false); + } + downloaded = true; + return new ArtworkSourceResult(tempPath, IsTemporary: true); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + return Errors.FileSystemManagement.FileNotFound; + } + finally + { + // Remove the partially downloaded temporary file when the download failed. + if (!downloaded && File.Exists(tempPath)) + File.Delete(tempPath); + } + } + + /// + /// Builds the file system path of the directory of the album artwork, under the internal media directory. + /// The artwork of the album is stored under the directory of its release type, mirroring the structure of the scanned files. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The name of the release type directory the album is stored under on disk, or to store the artwork directly under the artist directory. + /// An containing either the file system path of the album artwork directory, or an error. + private Result BuildAlbumArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName) + { + Result artistPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + if (artistPathResult.IsFailure) + return artistPathResult.Errors; + + // The release type directory groups the releases of an artist that share a title but are different releases, like the album and the single of the same songs. + Result albumParentPathResult = artistPathResult; + if (!string.IsNullOrWhiteSpace(releaseTypeName)) + { + Result releaseTypeSegmentResult = _pathService.SanitizeSegment(releaseTypeName); + if (releaseTypeSegmentResult.IsFailure) + return releaseTypeSegmentResult.Errors; + Result releaseTypePathResult = _pathService.CombinePath(artistPathResult.Value, releaseTypeSegmentResult.Value.Name); + if (releaseTypePathResult.IsFailure) + return releaseTypePathResult.Errors; + albumParentPathResult = releaseTypePathResult; + } + + Result albumSegmentResult = _pathService.SanitizeSegment($"{albumTitle}-{albumId}"); + if (albumSegmentResult.IsFailure) + return albumSegmentResult.Errors; + return _pathService.CombinePath(albumParentPathResult.Value, albumSegmentResult.Value.Name); + } + + /// + /// Builds the file system path of the directory of the artist artwork, under the internal media directory. + /// The artwork of the albums of the artist is stored in the subdirectories of this directory. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// An containing either the file system path of the artist artwork directory, or an error. + private Result BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName) + { + Result libraryPathResult = BuildLibraryArtworkDirectoryPath(libraryId, libraryName); + if (libraryPathResult.IsFailure) + return libraryPathResult.Errors; + + Result artistSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(artistName) ? "Unknown" : artistName); + if (artistSegmentResult.IsFailure) + return artistSegmentResult.Errors; + return _pathService.CombinePath(libraryPathResult.Value, artistSegmentResult.Value.Name); + } + + /// + /// Builds the file system path of the directory of a music media library, under the internal media directory. + /// + /// The Id of the media library. + /// The name of the media library. + /// An containing either the file system path of the media library directory, or an error. + private Result BuildLibraryArtworkDirectoryPath(Guid libraryId, string libraryName) + { + Result mediaRootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettings.RootDirectory); + if (mediaRootPathResult.IsFailure) + return mediaRootPathResult.Errors; + Result musicPathResult = _pathService.CombinePath(mediaRootPathResult.Value, _mediaSettings.MusicDirectory); + if (musicPathResult.IsFailure) + return musicPathResult.Errors; + + Result librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}"); + if (librarySegmentResult.IsFailure) + return librarySegmentResult.Errors; + return _pathService.CombinePath(musicPathResult.Value, librarySegmentResult.Value.Name); + } + + /// + /// Creates the directory at , along with its missing parents. + /// + /// The file system path of the directory to create. + /// An representing either a successful operation, or an error. + private Result EnsureDirectory(string directoryPath) + { + Result directoryPathIdResult = FileSystemPathId.Create(directoryPath); + if (directoryPathIdResult.IsFailure) + return directoryPathIdResult.Errors; + + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + return directoryExistsResult.Errors; + if (directoryExistsResult.Value) + return Result.Success; + + string? parentDirectoryPath = Path.GetDirectoryName(directoryPath); + if (!string.IsNullOrEmpty(parentDirectoryPath) && !string.Equals(parentDirectoryPath, directoryPath, StringComparison.Ordinal)) + { + Result createParentResult = EnsureDirectory(parentDirectoryPath); + if (createParentResult.IsFailure) + return createParentResult.Errors; + } + + Result parentDirectoryPathIdResult = FileSystemPathId.Create(parentDirectoryPath ?? directoryPath); + if (parentDirectoryPathIdResult.IsFailure) + return parentDirectoryPathIdResult.Errors; + + Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(parentDirectoryPathIdResult.Value, Path.GetFileName(directoryPath)); + if (createDirectoryResult.IsFailure) + return createDirectoryResult.Errors; + return Result.Success; + } + + /// + /// Describes the resolved local source of the artwork. + /// + /// The file system path of the resolved source. + /// Whether the resolved source is a temporary file that must be cleaned up after it is stored. + private sealed record ArtworkSourceResult(string Path, bool IsTemporary); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs new file mode 100644 index 00000000..000eb03c --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs @@ -0,0 +1,205 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; + +/// +/// Merges the music metadata returned by multiple metadata providers into a single metadata, giving priority to the first provider that provides a value for each field. +/// +internal static class MusicMetadataAggregator +{ + /// + /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields. + /// + /// The first artist metadata to merge, whose values have priority. + /// The second artist metadata, filling the fields that the first metadata lacks. + /// The merged artist metadata. + public static ArtistMetadataDto Merge(ArtistMetadataDto first, ArtistMetadataDto second) + { + return new ArtistMetadataDto( + First(first.Name, second.Name), + First(first.SortName, second.SortName), + First(first.Disambiguation, second.Disambiguation), + First(first.Type, second.Type), + First(first.Gender, second.Gender), + First(first.Country, second.Country), + First(first.Area, second.Area), + First(first.BeginArea, second.BeginArea), + First(first.EndArea, second.EndArea), + First(first.LifeSpanBegin, second.LifeSpanBegin), + First(first.LifeSpanEnd, second.LifeSpanEnd), + first.IsEnded || second.IsEnded, + First(first.Website, second.Website), + First(first.MusicBrainzArtistId, second.MusicBrainzArtistId), + Union(first.Ipis, second.Ipis, ipi => ipi), + Union(first.Isnis, second.Isnis, isni => isni), + Union(first.Aliases, second.Aliases, alias => alias.Name), + Union(first.Genres, second.Genres, genre => genre.Name), + Union(first.Tags, second.Tags, tag => tag.Name), + Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()), + Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role}")); + } + + /// + /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields. + /// + /// The first album metadata to merge, whose values have priority. + /// The second album metadata, filling the fields that the first metadata lacks. + /// The merged album metadata. + public static AlbumMetadataDto Merge(AlbumMetadataDto first, AlbumMetadataDto second) + { + return new AlbumMetadataDto( + First(first.Title, second.Title), + First(first.OriginalTitle, second.OriginalTitle), + First(first.Description, second.Description), + First(first.Disambiguation, second.Disambiguation), + MergeReleaseInfo(first.ReleaseInfo, second.ReleaseInfo), + First(first.Language, second.Language), + First(first.OriginalLanguage, second.OriginalLanguage), + Union(first.Tags, second.Tags, tag => tag.Name), + Union(first.Genres, second.Genres, genre => genre.Name), + First(first.Script, second.Script), + first.ReleaseTypes is { Count: > 0 } ? first.ReleaseTypes : second.ReleaseTypes, + First(first.ReleaseStatus, second.ReleaseStatus), + First(first.MediaFormat, second.MediaFormat), + First(first.Packaging, second.Packaging), + First(first.TotalDiscs, second.TotalDiscs), + First(first.TotalTracks, second.TotalTracks), + First(first.Barcode, second.Barcode), + Union(first.CatalogNumbers, second.CatalogNumbers, catalogNumber => catalogNumber), + First(first.Label, second.Label), + First(first.ASIN, second.ASIN), + First(first.MusicBrainzReleaseId, second.MusicBrainzReleaseId), + First(first.MusicBrainzReleaseGroupId, second.MusicBrainzReleaseGroupId), + First(first.MusicBrainzReleaseArtistId, second.MusicBrainzReleaseArtistId), + Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role}"), + Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()), + First(first.ReleaseTitle, second.ReleaseTitle)); + } + + /// + /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields. + /// + /// The first audio metadata to merge, whose values have priority. + /// The second audio metadata, filling the fields that the first metadata lacks. + /// The merged audio metadata. + public static AudioMetadataDto Merge(AudioMetadataDto first, AudioMetadataDto second) + { + return new AudioMetadataDto( + First(first.Title, second.Title), + First(first.OriginalTitle, second.OriginalTitle), + First(first.Description, second.Description), + First(first.Disambiguation, second.Disambiguation), + MergeReleaseInfo(first.ReleaseInfo, second.ReleaseInfo), + First(first.Language, second.Language), + First(first.OriginalLanguage, second.OriginalLanguage), + Union(first.Tags, second.Tags, tag => tag.Name), + Union(first.Genres, second.Genres, genre => genre.Name), + First(first.Script, second.Script), + First(first.Key, second.Key), + First(first.Bpm, second.Bpm), + first.IsVideo || second.IsVideo, + First(first.Work, second.Work), + Union(first.Isrcs, second.Isrcs, isrc => isrc.Value), + Union(first.Moods, second.Moods, mood => mood.Name), + First(first.DurationInSeconds, second.DurationInSeconds), + First(first.SampleRate, second.SampleRate), + First(first.Channels, second.Channels), + First(first.BitDepth, second.BitDepth), + First(first.AudioCodec, second.AudioCodec), + First(first.Bitrate, second.Bitrate), + First(first.MusicBrainzRecordingId, second.MusicBrainzRecordingId), + First(first.MusicBrainzTrackId, second.MusicBrainzTrackId), + Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role}"), + Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString())); + } + + /// + /// Merges the release information of the two metadata, keeping the first non-null value of each field. + /// + /// The first release information, whose values have priority. + /// The second release information, filling the fields that the first one lacks. + /// The merged release information, or when both are . + private static ReleaseInfoDto? MergeReleaseInfo(ReleaseInfoDto? first, ReleaseInfoDto? second) + { + if (first is null && second is null) + return null; + + DateOnly? originalReleaseDate = First(first?.OriginalReleaseDate, second?.OriginalReleaseDate); + int? originalReleaseYear = First(first?.OriginalReleaseYear, second?.OriginalReleaseYear); + DateOnly? reReleaseDate = First(first?.ReReleaseDate, second?.ReReleaseDate); + int? reReleaseYear = First(first?.ReReleaseYear, second?.ReReleaseYear); + + // A release date and its year describe the same point in time, so the year is derived from the date whenever a date is known. Without this, + // a year from one provider could be combined with a date from another (for example a release year from the tags with the original release + // date from MusicBrainz), and the resulting inconsistent pair would be rejected when the metadata is applied. + if (originalReleaseDate is not null) + originalReleaseYear = originalReleaseDate.Value.Year; + if (reReleaseDate is not null) + reReleaseYear = reReleaseDate.Value.Year; + + return new ReleaseInfoDto( + originalReleaseDate, + originalReleaseYear, + reReleaseDate, + reReleaseYear, + First(first?.ReleaseCountry, second?.ReleaseCountry), + First(first?.ReleaseVersion, second?.ReleaseVersion)); + } + + /// + /// Gets the first non-null value of the two values. + /// + /// The type of the values. + /// The value with priority. + /// The fallback value. + /// The first non-null value, or when both are . + private static T? First(T? first, T? second) + { + return first is not null && !IsEmpty(first) ? first : second; + } + + /// + /// Determines whether the provided value is an empty string. + /// + /// The type of the value. + /// The value to check. + /// when the value is an empty string, otherwise . + private static bool IsEmpty(T? value) + { + return value is string text && string.IsNullOrWhiteSpace(text); + } + + /// + /// Returns the union of the two collections, de-duplicated by the key, keeping the items of the first collection on key conflicts. + /// + /// The type of the collection items. + /// The first collection, whose items have priority. + /// The second collection. + /// The function used to extract the de-duplication key of an item. + /// The union of the two collections, or when both are . + private static List? Union(List? first, List? second, Func keySelector) + where T : class + { + if (first is null && second is null) + return null; + + Dictionary seen = new(StringComparer.OrdinalIgnoreCase); + List result = []; + + void AddRange(List? items) + { + foreach (T item in items ?? []) + if (seen.TryAdd(keySelector(item) ?? string.Empty, item)) + result.Add(item); + } + + AddRange(first); + AddRange(second); + return result; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs new file mode 100644 index 00000000..9e6c6f1e --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs @@ -0,0 +1,332 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Media library scan job for discovering music file system items. +/// +internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicFileSystemDiscoveryJob +{ + private const int STAGING_BATCH_SIZE = 1000; // The number of discovered files that are written to the staging results in a single batch, keeping the peak memory bounded regardless of the library size. + private static readonly HashSet s_audioExtensions = new( + [ + ".mp3", ".flac", ".m4a", ".aac", ".ogg", ".opus", + ".wav", ".wma", ".aiff", ".aif", ".ape", ".wv", + ".dsf", ".dff", ".mka" + ], + StringComparer.OrdinalIgnoreCase + ); + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + /// + public MusicFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The id of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). + int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); + // Only execute this job's payload when it has no parents, or when all the parents finished their execution. + if (Parents.Count == 0 || parentsCompleted == Parents.Count) + { + // This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // file system processing that takes time, and would block the processing of scan jobs in the in-memory queue. + await Task.Run(async () => + { + Status = LibraryScanJobStatus.Running; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService()!; + IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // Get the library from the repository. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + + // Convert it to a domain object. + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) + throw new InvalidOperationException(domainLibraryResult.FirstError.Description); + + // When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan. + Dictionary? fingerprintsByPath = null; + if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) + { + Result> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getFingerprintsResult.IsFailure) + throw new InvalidOperationException(getFingerprintsResult.FirstError.Description); + fingerprintsByPath = getFingerprintsResult.Value; + } + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); + DateTime lastHeartbeat = DateTime.UtcNow; + int processedContentLocations = 0; + + List stagingBatch = []; + List fingerprintBatch = []; + + // Get the files for each of the media library content locations. + foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) + { + cancellationToken.ThrowIfCancellationRequested(); + + await DiscoverContentLocationAsync( + contentLocation.Path, + fileProviderService, + directoryProviderService, + fingerprintsByPath is not null, + fingerprintsByPath, + stagingBatch, + fingerprintBatch, + unitOfWork.LibraryScanStagingResultsRepository, + unitOfWork.DirectoryScanFingerprintRepository, + cancellationToken).ConfigureAwait(false); + processedContentLocations++; + + // Increment the number of processed elements progress in a high-frequency counter with low overhead check. + DateTime now = DateTime.UtcNow; + if (now - lastHeartbeat >= heartbeatInterval) + { + publishJobProgressResult = await PublishJobProgressAsync( + domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastHeartbeat = now; + } + } + + // Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size. + if (stagingBatch.Count > 0) + { + Result insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + throw new InvalidOperationException(insertResult.FirstError.Description); + } + if (fingerprintBatch.Count > 0) + { + Result upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + throw new InvalidOperationException(upsertResult.FirstError.Description); + } + + // This job finished, increment the number of processed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Discovers the music files of a content location of the media library, using a breadth-first traversal, and writes them in batches to the staging results. + /// + /// The path of the root directory from which to start collecting files. + /// The service used to enumerate the files of a directory. + /// The service used to enumerate the subdirectories of a directory. + /// Whether to skip the directories whose last write time has not changed since the last scan, or not. + /// The directory scan fingerprints of the library, mapped by the directory path. Can be when the fast skip is disabled. + /// The batch of discovered files that is written to the staging results when it reaches the batch size. + /// The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size. + /// The repository used to write the discovered files to the staging results. + /// The repository used to write the directory scan fingerprints to the storage medium. + /// Cancellation token that can be used to stop the execution. + /// + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md for details. + /// + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + private async Task DiscoverContentLocationAsync( + string rootDirectoryPath, + IFileProviderService fileProviderService, + IDirectoryProviderService directoryProviderService, + bool shouldSkipUnchangedDirectories, + Dictionary? fingerprintsByPath, + List stagingBatch, + List fingerprintBatch, + ILibraryScanStagingResultsRepository stagingResultsRepository, + IDirectoryScanFingerprintRepository directoryScanFingerprintRepository, + CancellationToken cancellationToken) + { + Result rootPathResult = FileSystemPathId.Create(rootDirectoryPath); + if (rootPathResult.IsFailure) + return; + + Queue directoryQueue = new(); + directoryQueue.Enqueue(rootPathResult.Value); + + // Use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory + // and could result in stack overflow on deeply nested directories. + while (directoryQueue.Count > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + FileSystemPathId currentDirectory = directoryQueue.Dequeue(); + + // When the fast skip is enabled, skip the whole subtree of a directory whose last write time has not changed since the last scan. + if (shouldSkipUnchangedDirectories) + { + Result> getLastWriteTimeResult = directoryProviderService.GetLastWriteTime(currentDirectory); + DateTime currentLastWriteTimeUtc = getLastWriteTimeResult.IsSuccess && getLastWriteTimeResult.Value.HasValue + ? getLastWriteTimeResult.Value.Value + : DateTime.MinValue; + if (fingerprintsByPath is not null && + fingerprintsByPath.TryGetValue(currentDirectory.Path, out DirectoryScanFingerprintEntity? fingerprint) && + fingerprint.LastWriteTimeUtc == currentLastWriteTimeUtc) + continue; + + fingerprintBatch.Add(new DirectoryScanFingerprintEntity() + { + Id = Guid.NewGuid(), + LibraryId = LibraryId.Value, + Path = currentDirectory.Path, + LastWriteTimeUtc = currentLastWriteTimeUtc + }); + // Flush the collected directory scan fingerprints in bounded batches, so that the memory usage stays proportional to the batch size, no matter how many directories the library has. + if (fingerprintBatch.Count >= STAGING_BATCH_SIZE) + { + Result upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + if (upsertFingerprintsResult.IsFailure) + throw new InvalidOperationException(upsertFingerprintsResult.FirstError.Description); + fingerprintBatch.Clear(); + } + } + + // Process the files of the current directory. + Result> getFilesResult = fileProviderService.GetFilePaths(currentDirectory, true); + if (getFilesResult.IsSuccess) + { + foreach (FileSystemPathId filePath in getFilesResult.Value) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!s_audioExtensions.Contains(Path.GetExtension(filePath.Path))) + continue; + + long size = 0; + Result getSizeResult = fileProviderService.GetSize(filePath); + if (getSizeResult.IsSuccess && getSizeResult.Value.HasValue) + size = getSizeResult.Value.Value; + + long ticks = 0; + Result> getFileLastWriteTimeResult = fileProviderService.GetLastWriteTime(filePath); + if (getFileLastWriteTimeResult.IsSuccess && getFileLastWriteTimeResult.Value.HasValue) + ticks = getFileLastWriteTimeResult.Value.Value.Ticks; + + stagingBatch.Add(new LibraryScanStagingResultsEntity() + { + Id = Guid.NewGuid(), + LibraryScanId = ScanId.Value, + Path = filePath.Path, + Size = size, + Ticks = ticks, + ContentHash = 0, + PreviousContentHash = 0, + NeedsRehash = true, + IsNew = true + }); + if (stagingBatch.Count >= STAGING_BATCH_SIZE) + { + Result insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertBatchResult.IsFailure) + throw new InvalidOperationException(insertBatchResult.FirstError.Description); + stagingBatch.Clear(); + } + } + } + + // Process the subdirectories - each new subdirectory is added to the same queue, for later processing. + Result> getSubdirectoriesResult = directoryProviderService.GetSubdirectoryPaths(currentDirectory, true); + if (getSubdirectoriesResult.IsSuccess) + { + foreach (FileSystemPathId subdirectory in getSubdirectoriesResult.Value) + { + cancellationToken.ThrowIfCancellationRequested(); + directoryQueue.Enqueue(subdirectory); + } + } + } + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs new file mode 100644 index 00000000..714a60f4 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Derives the structure of a music library on disk from the file system path of a music file. +/// +internal sealed class MusicLibraryPathStructure +{ + /// + /// Matches the name of a directory that holds one disc of a multi-disc album, like "Disc 1" or "CD2". + /// + private static readonly Regex s_discDirectoryPattern = new(@"^(?:disk|disc|cd)\s*\d+$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private readonly IPathService _pathService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to determine the path separator of the current platform. + public MusicLibraryPathStructure(IPathService pathService) + { + _pathService = pathService; + } + + /// + /// Gets the on-disk directory of the album the track stored at belongs to. + /// A multi-disc album nests its tracks in disc subdirectories, so the directory of a disc is skipped in favor of its parent. + /// + /// The file system path of the track whose album directory is retrieved. + /// The file system path of the album directory, or the directory of the track when it cannot be resolved. + public string GetAlbumDirectory(string trackPath) + { + if (string.IsNullOrEmpty(trackPath)) + return trackPath; + + string? trackDirectory = GetParentDirectoryPath(trackPath); + if (string.IsNullOrEmpty(trackDirectory)) + return trackPath; + + if (!s_discDirectoryPattern.IsMatch(GetLastSegment(trackDirectory))) + return trackDirectory; + + string? albumDirectory = GetParentDirectoryPath(trackDirectory); + return string.IsNullOrEmpty(albumDirectory) ? trackDirectory : albumDirectory; + } + + /// + /// Gets the name of the on-disk release type directory of the track stored at , 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 + /// directory of a flat library is not mistaken for a release type. + /// + /// The file system path of the track whose release type directory is retrieved. + /// The name of the on-disk release type directory, or when the library does not use one. + public string? GetReleaseTypeDirectoryName(string trackPath) + { + string albumDirectory = GetAlbumDirectory(trackPath); + string? releaseTypeDirectory = GetParentDirectoryPath(albumDirectory); + if (string.IsNullOrEmpty(releaseTypeDirectory)) + return null; + + string releaseTypeName = GetLastSegment(releaseTypeDirectory); + return Enum.TryParse(releaseTypeName, ignoreCase: true, out MusicReleaseType _) ? releaseTypeName : null; + } + + /// + /// Gets the parent directory of the file or directory stored at , using the path separator of the current platform. + /// + /// The path whose parent directory is retrieved. + /// The parent directory of the path, or when the path has no parent directory. + private string? GetParentDirectoryPath(string path) + { + string trimmedPath = path.TrimEnd(_pathService.PathSeparator); + int lastSeparatorIndex = trimmedPath.LastIndexOf(_pathService.PathSeparator); + if (lastSeparatorIndex <= 0) + return null; + return trimmedPath[..lastSeparatorIndex]; + } + + /// + /// Gets the last segment, the file or directory name, of , using the path separator of the current platform. + /// + /// The path whose last segment is retrieved. + /// The last segment of the path. + private string GetLastSegment(string path) + { + string trimmedPath = path.TrimEnd(_pathService.PathSeparator); + int lastSeparatorIndex = trimmedPath.LastIndexOf(_pathService.PathSeparator); + return lastSeparatorIndex < 0 ? trimmedPath : trimmedPath[(lastSeparatorIndex + 1)..]; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs new file mode 100644 index 00000000..17ff4a58 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs @@ -0,0 +1,680 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Artwork enricher for the media library items of the music media library type, using the artwork providers configured for the media library. +/// +/// +/// The artwork of an artist and of an album is tracked per type and ordinal, so that a change of one piece of artwork does not require the others to be re-fetched. +/// +internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanArtworkEnricher +{ + private const int ENRICHMENT_PAGE_SIZE = 200; // The number of artists or albums that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + private readonly MusicLibraryPathStructure _musicLibraryPathStructure; + + /// + /// The media library type that this artwork enricher supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Music; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating scopes in which services are requested. + /// Injected logger used to report the issues encountered while resolving the artwork. + /// Injected service used to derive the release type directory of the tracks from their file system paths. + public MusicMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger, MusicLibraryPathStructure musicLibraryPathStructure) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + _musicLibraryPathStructure = musicLibraryPathStructure; + } + + /// + /// Resolves the artwork of the artists and the albums of the provided media library, using the artwork providers configured for it. + /// + /// The unique identifier of the media library whose artwork is resolved. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken) + { + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId); + + // Load the media library, whose name is used to build the directories of the artwork, and whose setting determines whether the providers that require access to the web are used during the enrichment. + string libraryName = string.Empty; + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the artwork will not be stored and the providers requiring the web will not be used."); + else + { + libraryName = getLibraryResult.Value.Title; + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + } + + // Read whether the artwork of the items of the user is aggregated from multiple providers, when it is missing. + bool shouldAggregateArtworkWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) + { + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the artwork will not be aggregated across providers."); + else + shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false; + } + + // Get the artwork providers configured for the media library, in their configured order, that support the media library type. + // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding. + List artworkProviders = []; + if (unitOfWork.ArtworkProviderConfigurationRepository is not null) + { + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + _logger.LogWarning("Failed to read the artwork provider configurations."); + else + { + foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music); + artworkProviders.AddRange(configuredProviders); + } + } + } + + // When no artwork provider is available, the items must not be marked as failed to resolve, so the enrichment is skipped entirely. + if (artworkProviders.Count == 0) + { + _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value); + return; + } + + // The providers are split by the lookup they accept, keeping the configured rank order in which they were gathered. + IReadOnlyList artistProviders = [.. artworkProviders.Where(provider => provider is IArtworkProvider)]; + IReadOnlyList albumProviders = [.. artworkProviders.Where(provider => provider is IArtworkProvider)]; + + IMusicArtworkService? musicArtworkService = asyncServiceScope.ServiceProvider.GetService(); + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + + int totalArtistsToEnrich = 0; + if (artistProviders.Count > 0) + { + Result getArtistsToEnrichCountResult = await unitOfWork.ArtistRepository.GetArtistsNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtistsToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getArtistsToEnrichCountResult.FirstError.Description); + totalArtistsToEnrich = getArtistsToEnrichCountResult.Value; + } + + int totalAlbumsToEnrich = 0; + if (albumProviders.Count > 0) + { + Result getAlbumsToEnrichCountResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getAlbumsToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getAlbumsToEnrichCountResult.FirstError.Description); + totalAlbumsToEnrich = getAlbumsToEnrichCountResult.Value; + } + + int totalItemsToEnrich = totalArtistsToEnrich + totalAlbumsToEnrich; + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedItemsCount = 0; + + // Reports that a single artist or album was processed, publishing the progress at most once per interval. + async Task ReportItemProcessedAsync() + { + int processedItems = Interlocked.Increment(ref processedItemsCount); + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + Result publishItemProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, processedItems, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishItemProgressResult.IsFailure) + throw new InvalidOperationException(publishItemProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + if (artistProviders.Count > 0) + await EnrichArtistsAsync(libraryId, artistProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, ReportItemProcessedAsync, cancellationToken).ConfigureAwait(false); + + if (albumProviders.Count > 0) + await EnrichAlbumsAsync(libraryId, albumProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, ReportItemProcessedAsync, cancellationToken).ConfigureAwait(false); + + // The enrichment finished, force the progress to reach its total, so that a throttled update cannot leave it incomplete. + Result publishFinalProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, totalItemsToEnrich, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishFinalProgressResult.IsFailure) + throw new InvalidOperationException(publishFinalProgressResult.FirstError.Description); + } + + /// + /// Resolves the artwork of the artists of the provided media library whose artwork has not been resolved yet, page by page. + /// + /// The unique identifier of the media library whose artists are enriched. + /// The artists artwork providers, in the order they are consulted. + /// The service used to store the artwork of the artists. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the artists belong to. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the artists. + /// The callback invoked after each artist is processed, to advance the progress. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + private async Task EnrichArtistsAsync(LibraryId libraryId, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, Func reportItemProcessedAsync, CancellationToken cancellationToken) + { + string? lastName = null; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getArtistsPageResult = await unitOfWork.ArtistRepository.GetArtistsNeedingArtworkAsync(libraryId.Value, lastName, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getArtistsPageResult.IsFailure) + throw new InvalidOperationException(getArtistsPageResult.FirstError.Description); + IReadOnlyList artistsPage = getArtistsPageResult.Value; + if (artistsPage.Count == 0) + break; + + foreach (ArtistEntity artistEntity in artistsPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + // The first track of the artist, in a deterministic order, describes the artist in the artwork lookup and locates its directory on the file system. + string firstTrackPath = artistEntity.Albums.SelectMany(album => album.Tracks).Select(track => track.Path).OrderBy(path => path).FirstOrDefault() ?? string.Empty; + await EnrichArtistArtworkAsync(artistEntity, firstTrackPath, artworkProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false); + await reportItemProcessedAsync().ConfigureAwait(false); + } + + // Persist the resolved artwork of this page, then detach it from the change tracker, keeping the peak memory bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); + unitOfWork.ClearTrackedEntities(); + + lastName = artistsPage[^1].Name; + } + } + + /// + /// Resolves the artwork of the albums of the provided media library whose artwork has not been resolved yet, page by page. + /// + /// The unique identifier of the media library whose albums are enriched. + /// The album artwork providers, in the order they are consulted. + /// The service used to store the artwork of the albums. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the albums belong to. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the albums. + /// The callback invoked after each album is processed, to advance the progress. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + private async Task EnrichAlbumsAsync(LibraryId libraryId, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, Func reportItemProcessedAsync, CancellationToken cancellationToken) + { + // A provider that does not require the web, like the one that reads the files of the user, can resolve the artwork without any MusicBrainz identifier. + bool canResolveWithoutMusicBrainzIds = artworkProviders.Any(provider => !provider.RequiresWebAccess); + + // The albums that were attempted but remain unresolved are tracked and excluded from the following pages, so that a page that made no album reach a terminal state cannot make the pagination loop forever. + List albumsRemainingUnresolved = []; + + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getAlbumsPageResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingArtworkAsync(libraryId.Value, albumsRemainingUnresolved, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getAlbumsPageResult.IsFailure) + throw new InvalidOperationException(getAlbumsPageResult.FirstError.Description); + IReadOnlyList albumsPage = getAlbumsPageResult.Value; + if (albumsPage.Count == 0) + break; + + // Load the path of one track of each album of this page, in one query, since it is used to locate the album directory on the file system. + Result> getTrackPathsResult = await unitOfWork.AlbumRepository.GetFirstTrackPathsByAlbumIdsAsync([.. albumsPage.Select(album => album.Id)], cancellationToken).ConfigureAwait(false); + if (getTrackPathsResult.IsFailure) + throw new InvalidOperationException(getTrackPathsResult.FirstError.Description); + + foreach (AlbumEntity albumEntity in albumsPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + string firstTrackPath = getTrackPathsResult.Value.TryGetValue(albumEntity.Id, out string? trackPath) ? trackPath : string.Empty; + bool isTerminal = await EnrichAlbumArtworkAsync(albumEntity, firstTrackPath, artworkProviders, musicArtworkService, fileHashService, libraryName, canResolveWithoutMusicBrainzIds, shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false); + if (!isTerminal) + albumsRemainingUnresolved.Add(albumEntity.Id); + await reportItemProcessedAsync().ConfigureAwait(false); + } + + // Persist the enriched albums of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); + unitOfWork.ClearTrackedEntities(); + } + } + + /// + /// Resolves the artwork of the provided from the , storing the artwork resolved from the providers, in their order. + /// + /// The artist whose artwork is resolved. + /// The file system path of one track of the artist, used to locate its directory. + /// The artist artwork providers, in the order they are consulted. + /// The service used to store the artwork of the artist. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the artist belongs to. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the artist. + /// Cancellation token that can be used to stop the execution. + /// when the artist reached a terminal artwork state, otherwise . + private async Task EnrichArtistArtworkAsync(ArtistEntity artistEntity, string firstTrackPath, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken) + { + ArtistMetadataLookupDto artworkLookup = new( + LibraryId: artistEntity.LibraryId, + Path: firstTrackPath, + MusicBrainzArtistId: artistEntity.MusicBrainzArtistId, + Name: artistEntity.Name); + + string artistName = artistEntity.Name; + + return await EnrichArtworkAsync( + artworkLookup, + MusicArtworkOwnerType.Artist, + artistEntity.Id, + artistName, + artworkProviders, + musicArtworkService, + fileHashService, + () => musicArtworkService!.DeleteArtistArtwork(artistEntity.LibraryId, libraryName, artistName), + (artwork, token) => musicArtworkService!.SaveArtistArtworkAsync(artistEntity.LibraryId, libraryName, artistName, artwork, token), + shouldAggregateArtworkWhenMissing, + unitOfWork, + cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the artwork of the provided from the , storing the artwork resolved from the providers, in their order. + /// + /// The album whose artwork is resolved. + /// The file system path of one track of the album, used to locate its directory. + /// The album artwork providers, in the order they are consulted. + /// The service used to store the artwork of the album. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the album belongs to. + /// Whether a provider that does not require the web can resolve the artwork without any MusicBrainz identifier. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the album. + /// Cancellation token that can be used to stop the execution. + /// when the album reached a terminal artwork state, otherwise . + private async Task EnrichAlbumArtworkAsync(AlbumEntity albumEntity, string firstTrackPath, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool canResolveWithoutMusicBrainzIds, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken) + { + // Without any MusicBrainz identifier, only a provider that reads the files of the user can resolve the artwork, so the album is left for a following scan otherwise. + if (albumEntity.MusicBrainzReleaseId is null && albumEntity.MusicBrainzReleaseGroupId is null && !canResolveWithoutMusicBrainzIds) + return false; + + AlbumMetadataLookupDto artworkLookup = new( + LibraryId: albumEntity.LibraryId, + Path: firstTrackPath, + MusicBrainzReleaseGroupId: albumEntity.MusicBrainzReleaseGroupId, + MusicBrainzReleaseId: albumEntity.MusicBrainzReleaseId, + Title: albumEntity.Title, + ArtistName: albumEntity.Artist?.Name, + ReleaseYear: albumEntity.OriginalReleaseYear, + TrackCount: albumEntity.TotalTracks); + + string artistName = albumEntity.Artist?.Name ?? string.Empty; + + // 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. + string? releaseTypeName = _musicLibraryPathStructure.GetReleaseTypeDirectoryName(firstTrackPath); + + return await EnrichArtworkAsync( + artworkLookup, + MusicArtworkOwnerType.Album, + albumEntity.Id, + albumEntity.Title, + artworkProviders, + musicArtworkService, + fileHashService, + () => musicArtworkService!.DeleteAlbumArtwork(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, releaseTypeName), + (artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, artwork, token, releaseTypeName), + shouldAggregateArtworkWhenMissing, + unitOfWork, + cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the artwork of the media item described by from the , in their order, replacing the stored artwork of the item. + /// + /// The lookup describing the media item whose artwork is resolved. + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// The description of the owner, used to report the issues encountered. + /// The artwork providers, in the order they are consulted. + /// The service used to store the artwork of the owner. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The action that deletes the artwork of the owner from the internal media directory. + /// The action that stores a piece of artwork of the owner into the internal media directory. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the owner. + /// Cancellation token that can be used to stop the execution. + /// when the owner reached a terminal artwork state, otherwise . + private async Task EnrichArtworkAsync(MetadataLookupDto artworkLookup, MusicArtworkOwnerType ownerType, Guid ownerId, string ownerDescription, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, Func> deleteStoredArtwork, Func>> saveArtworkAsync, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken) + { + if (musicArtworkService is null || unitOfWork.MusicArtworkRepository is null) + return false; + + ArtworkResolution resolution = await ResolveArtworkAsync(artworkLookup, artworkProviders, ownerDescription, shouldAggregateArtworkWhenMissing, cancellationToken).ConfigureAwait(false); + + // Replace the stored artwork of the owner as a whole, so that a piece of artwork that no longer exists at the source does not linger. + Result deleteStoredArtworkResult = deleteStoredArtwork(); + if (deleteStoredArtworkResult.IsFailure) + { + _logger.LogWarning("Failed to clear the stored artwork files of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription); + DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork)); + return false; + } + Result deleteEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); + if (deleteEntitiesResult.IsFailure) + { + _logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription); + DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork)); + return false; + } + + List artworkEntities = []; + + if (resolution.Artworks.Count > 0) + { + foreach (ResolvedArtwork resolvedArtwork in resolution.Artworks) + { + ArtworkDto artwork = resolvedArtwork.Artwork; + Result saveArtworkResult = await saveArtworkAsync(artwork, cancellationToken).ConfigureAwait(false); + if (saveArtworkResult.IsFailure) + { + _logger.LogWarning("Failed to store the {ArtworkType} artwork of the {OwnerType} '{OwnerDescription}'.", artwork.Type, ownerType, ownerDescription); + continue; + } + + string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\')); + ulong contentHash = fileHashService.ComputeFileHash(storedArtworkPath); + artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, artwork.Type, artwork.Ordinal, saveArtworkResult.Value, contentHash, ArtworkStatus.Enriched, resolvedArtwork.ProviderName)); + } + + // When every resolved piece of artwork failed to be stored, the owner is treated as failed to resolve, so that it is retried. + if (artworkEntities.Count == 0) + { + artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, ArtworkStatus.Failed, null)); + await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false); + return false; + } + } + else + { + // No artwork exists for the owner when a provider answered and found none, which is not a failure; it only failed when no provider could answer. + ArtworkStatus status = resolution.HasResolved ? ArtworkStatus.NotAvailable : ArtworkStatus.Failed; + artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, status, null)); + await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false); + return status == ArtworkStatus.NotAvailable; + } + + await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false); + return true; + } + + /// + /// Persists the provided pieces of of a music library item. + /// + /// The unit of work used to persist the artwork. + /// The pieces of artwork to persist. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + private async Task PersistArtworkAsync(IUnitOfWork unitOfWork, List artworkEntities, CancellationToken cancellationToken) + { + Result insertArtworkResult = await unitOfWork.MusicArtworkRepository.InsertRangeAsync(artworkEntities, cancellationToken).ConfigureAwait(false); + if (insertArtworkResult.IsFailure) + _logger.LogWarning("Failed to persist the resolved artwork of a music library item."); + } + + /// + /// Deletes the temporary files of the provided , used when the resolved artwork is not stored, so the temporary files do not linger. + /// + /// The resolved artworks whose temporary files are deleted. + private static void DeleteTemporaryArtworks(IEnumerable artworks) + { + foreach (ArtworkDto artwork in artworks) + { + if (!artwork.IsTemporary || string.IsNullOrWhiteSpace(artwork.LocalPath)) + continue; + try + { + if (File.Exists(artwork.LocalPath)) + File.Delete(artwork.LocalPath); + } + 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. + } + } + } + + /// + /// Resolves the artwork of the media item described by from the , + /// either aggregating the providers when is set, or using the first provider that supplies artwork otherwise. + /// + /// The lookup describing the media item whose artwork is resolved. + /// The artwork providers, in the order they are consulted. + /// The description of the owner, used to report the issues encountered. + /// Whether the artwork of every provider is combined, or only the first provider that supplies artwork is used. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all, distinguishing a confirmed absence of artwork from a resolution failure. + private async Task ResolveArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, bool shouldAggregateArtworkWhenMissing, CancellationToken cancellationToken) + { + if (shouldAggregateArtworkWhenMissing) + return await ResolveAggregatedArtworkAsync(lookup, artworkProviders, ownerDescription, cancellationToken).ConfigureAwait(false); + return await ResolveFirstArtworkAsync(lookup, artworkProviders, ownerDescription, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the artwork of the media item described by from the first provider that supplies some, in their order. + /// + /// The lookup describing the media item whose artwork is resolved. + /// The artwork providers, in the order they are consulted. + /// The description of the owner, used to report the issues encountered. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all. + private async Task ResolveFirstArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, CancellationToken cancellationToken) + { + bool hasResolved = false; + bool hasFailed = false; + foreach (IArtworkProvider provider in artworkProviders) + { + IReadOnlyList providerArtworks; + try + { + providerArtworks = await provider.GetArtworkAsync(lookup, cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) + { + // A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. + hasFailed = true; + _logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription); + continue; + } + + hasResolved = true; + // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract. + List usableArtworks = [.. providerArtworks + .Where(artwork => string.IsNullOrWhiteSpace(artwork.RemoteUrl) || provider.RequiresWebAccess) + .Select(artwork => new ResolvedArtwork(artwork, provider.Name))]; + if (usableArtworks.Count > 0) + return new ArtworkResolution(usableArtworks, HasResolved: true); + } + + // An empty result is only treated as a confirmed absence of artwork when at least one provider answered; when every provider failed, it is a failure. + return new ArtworkResolution([], HasResolved: hasResolved || !hasFailed); + } + + /// + /// Resolves the artwork of the media item described by from every provider, in their order, + /// combining them so that a provider only fills the artwork the providers before it did not supply. + /// + /// The lookup describing the media item whose artwork is resolved. + /// The artwork providers, in the order they are consulted. + /// The description of the owner, used to report the issues encountered. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all. + private async Task ResolveAggregatedArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, CancellationToken cancellationToken) + { + bool hasResolved = false; + bool hasFailed = false; + List resolvedArtworks = []; + HashSet<(ArtworkType Type, int Ordinal)> resolvedKeys = []; + foreach (IArtworkProvider provider in artworkProviders) + { + IReadOnlyList providerArtworks; + try + { + providerArtworks = await provider.GetArtworkAsync(lookup, cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) + { + // A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. + hasFailed = true; + _logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription); + continue; + } + + hasResolved = true; + foreach (ArtworkDto artwork in providerArtworks) + { + // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract. + if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess) + continue; + // The providers are consulted in their configured order, so a provider only fills the artwork the higher ranked ones did not supply, and a provider + // that holds just a part of the artwork of the item, like the local files of the user, is complemented by the providers that follow it. + if (resolvedKeys.Add((artwork.Type, artwork.Ordinal))) + resolvedArtworks.Add(new ResolvedArtwork(artwork, provider.Name)); + } + } + + // An empty result is only treated as a confirmed absence of artwork when at least one provider answered; when every provider failed, it is a failure. + return new ArtworkResolution(resolvedArtworks, HasResolved: hasResolved || !hasFailed); + } + + /// + /// Creates a piece of artwork of the music library item of the provided identified by . + /// + /// The Id of the music library item the artwork belongs to. + /// The type of the music library item the artwork belongs to. + /// The type of the artwork. + /// The ordinal of the artwork within its type. + /// The relative file name of the stored artwork, if the artwork has been resolved. + /// The content hash of the stored artwork. + /// The status of the artwork enrichment. + /// The name of the plugin that resolved the artwork, if applicable. + /// The created artwork entity. + private static MusicArtworkEntity CreateArtworkEntity(Guid ownerId, MusicArtworkOwnerType ownerType, ArtworkType artworkType, int ordinal, string? fileName, ulong contentHash, ArtworkStatus status, string? provider) + { + return new MusicArtworkEntity + { + Id = Guid.NewGuid(), + OwnerType = ownerType, + OwnerId = ownerId, + ArtworkType = artworkType, + Ordinal = ordinal, + FileName = fileName, + ContentHash = contentHash, + Status = status, + Provider = provider, + LastUpdateUtc = DateTime.UtcNow, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The unique identifier of the media library being scanned. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } + + /// + /// The artwork resolved for a music library item, each with the provider that supplied it, and whether a provider answered at all. + /// + /// The resolved artworks of the item, each with the provider that supplied it. + /// Whether at least one provider answered, confirming that any absence of artwork is real rather than a failure. + private sealed record ArtworkResolution(IReadOnlyList Artworks, bool HasResolved); + + /// + /// A piece of artwork of a music library item, together with the provider that supplied it. + /// + /// The resolved artwork. + /// The name of the provider that supplied the artwork. + private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs new file mode 100644 index 00000000..1eaf37a6 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs @@ -0,0 +1,326 @@ +#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.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Materializer for the media library items of the music media library type. +/// +internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanItemMaterializer +{ + private const string UNKNOWN_ARTIST_NAME = "Unknown Artist"; + private const string UNKNOWN_ALBUM_TITLE = "Unknown Album"; + + private readonly MusicLibraryPathStructure _musicLibraryPathStructure; + private readonly IPathService _pathService; + + /// + /// The media library type that this materializer supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Music; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to derive the album directory of the tracks from their file system paths. + /// Injected service used to derive the file name of a track from its file system path. + public MusicMediaLibraryScanItemMaterializer(MusicLibraryPathStructure musicLibraryPathStructure, IPathService pathService) + { + _musicLibraryPathStructure = musicLibraryPathStructure; + _pathService = pathService; + } + + /// + /// Resets the enrichment state of the tracks stored at the provided , together with their albums and artists. + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose tracks are reset. + /// The file system paths of the tracks whose enrichment state is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetEnrichmentStateForChangedPathsAsync(IUnitOfWork unitOfWork, Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken) + { + return await unitOfWork.TrackRepository.ResetEnrichmentStateForPathsAsync(libraryId, paths, cancellationToken).ConfigureAwait(false); + } + + /// + /// Materializes the artists, albums and tracks of the media library from the metadata staged for the media library scan. + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose items are materialized. + /// The Id of the media library scan whose results are materialized. + /// The file system paths of the media library scan snapshot. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList paths, CancellationToken cancellationToken) + { + // The staged metadata of the scan holds everything needed to materialize the music library items, grouped by artist and by release. + Result> getStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.GetByScanIdAsync(scanId, cancellationToken).ConfigureAwait(false); + if (getStagedMetadataResult.IsFailure) + return getStagedMetadataResult.Errors; + IReadOnlyList stagedMetadata = getStagedMetadataResult.Value; + if (stagedMetadata.Count == 0) + return Result.Success; + + // Tracks that are already stored are never inserted again, so a re-scan of an unchanged file does not duplicate its track. + List stagedPaths = [.. stagedMetadata.Select(stagedItem => stagedItem.Path)]; + Result> getExistingPathsResult = await unitOfWork.TrackRepository.GetExistingPathsAsync(libraryId, stagedPaths, cancellationToken).ConfigureAwait(false); + if (getExistingPathsResult.IsFailure) + return getExistingPathsResult.Errors; + HashSet existingPaths = [.. getExistingPathsResult.Value]; + + // The artists of a library are uniquely identified by their name, so they are grouped by it, otherwise two groups named alike would collide with + // the unique index of the artists; the MusicBrainz identifier of the group is the one of the release artist, because the artist of the music + // library is the artist the release, and not the individual tracks, belong to. Albums are grouped by the on-disk directory of their tracks, + // because the directory is the source of truth of what an album is: the tracks of one folder that disagree on their MusicBrainz release + // identifier, or that carry none, still belong to the same album. + foreach (IGrouping artistGroup in stagedMetadata.GroupBy(GetArtistName)) + { + cancellationToken.ThrowIfCancellationRequested(); + + string artistName = artistGroup.Key; + Guid? musicBrainzArtistId = artistGroup.Select(stagedItem => stagedItem.MusicBrainzReleaseArtistId ?? stagedItem.MusicBrainzArtistId).FirstOrDefault(musicBrainzId => musicBrainzId is not null); + + Result getArtistResult = await unitOfWork.ArtistRepository.GetByNameAsync(libraryId, artistName, cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + ArtistEntity? existingArtist = getArtistResult.Value; + + // A brand new artist is accumulated together with all its new albums, so that the whole aggregate is inserted in a single call. + ArtistEntity? newArtist = null; + + foreach (IGrouping albumGroup in artistGroup.GroupBy(stagedItem => _musicLibraryPathStructure.GetAlbumDirectory(stagedItem.Path), StringComparer.OrdinalIgnoreCase)) + { + List albumStagedItems = [.. albumGroup]; + string albumTitle = GetAlbumTitle(albumStagedItems[0]); + string albumDirectory = _musicLibraryPathStructure.GetAlbumDirectory(albumStagedItems[0].Path); + Guid? musicBrainzReleaseId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseId).FirstOrDefault(musicBrainzId => musicBrainzId is not null); + Guid? musicBrainzReleaseGroupId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseGroupId).FirstOrDefault(musicBrainzId => musicBrainzId is not null); + Guid? musicBrainzReleaseArtistId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseArtistId).FirstOrDefault(musicBrainzId => musicBrainzId is not null); + + // Only the tracks that are not stored yet are materialized, the others already have their own track row. + List tracksToInsert = [.. albumStagedItems.Where(stagedItem => !existingPaths.Contains(stagedItem.Path))]; + if (tracksToInsert.Count == 0) + continue; + + if (existingArtist is null) + { + newArtist ??= CreateArtistEntity(libraryId, artistName, musicBrainzArtistId); + AlbumEntity newAlbum = CreateAlbumEntity(libraryId, newArtist.Id, albumTitle, albumStagedItems, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId); + foreach (MusicLibraryScanItemMetadataEntity stagedItem in tracksToInsert) + newAlbum.Tracks.Add(CreateTrackEntity(libraryId, newAlbum.Id, stagedItem)); + newAlbum.TotalTracks = newAlbum.Tracks.Count; + newArtist.Albums.Add(newAlbum); + } + else + { + // The directory pins the album of the artist, so releases that share a title but live in different folders are not merged. + Result getAlbumResult = await unitOfWork.AlbumRepository.GetByTrackDirectoryAsync(existingArtist.Id, albumDirectory, cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + AlbumEntity? existingAlbum = getAlbumResult.Value; + + // A library materialized before the directories became the grouping key is matched by title instead. + if (existingAlbum is null) + { + getAlbumResult = await unitOfWork.AlbumRepository.GetByTitleAsync(existingArtist.Id, albumTitle, cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + existingAlbum = getAlbumResult.Value; + } + + if (existingAlbum is null) + { + AlbumEntity newAlbum = CreateAlbumEntity(libraryId, existingArtist.Id, albumTitle, albumStagedItems, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId); + foreach (MusicLibraryScanItemMetadataEntity stagedItem in tracksToInsert) + newAlbum.Tracks.Add(CreateTrackEntity(libraryId, newAlbum.Id, stagedItem)); + newAlbum.TotalTracks = newAlbum.Tracks.Count; + Result insertAlbumResult = await unitOfWork.AlbumRepository.InsertAsync(newAlbum, cancellationToken).ConfigureAwait(false); + if (insertAlbumResult.IsFailure) + return insertAlbumResult.Errors; + } + else + { + foreach (MusicLibraryScanItemMetadataEntity stagedItem in tracksToInsert) + { + TrackEntity newTrack = CreateTrackEntity(libraryId, existingAlbum.Id, stagedItem); + Result insertTrackResult = await unitOfWork.TrackRepository.InsertAsync(newTrack, cancellationToken).ConfigureAwait(false); + if (insertTrackResult.IsFailure) + return insertTrackResult.Errors; + } + } + } + } + + if (newArtist is not null) + { + Result insertArtistResult = await unitOfWork.ArtistRepository.InsertAsync(newArtist, cancellationToken).ConfigureAwait(false); + if (insertArtistResult.IsFailure) + return insertArtistResult.Errors; + } + } + + // The staged metadata of the scan was consumed, so it is removed, keeping the storage medium bounded across scans. + Result deleteStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.DeleteByScanIdAsync(scanId, cancellationToken).ConfigureAwait(false); + if (deleteStagedMetadataResult.IsFailure) + return deleteStagedMetadataResult.Errors; + + return Result.Success; + } + + /// + /// Resets the metadata enrichment status of all the artists, albums and tracks of the media library identified by . + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose items are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetMetadataStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken) + { + Result resetArtistsResult = await unitOfWork.ArtistRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (resetArtistsResult.IsFailure) + return resetArtistsResult.Errors; + Result resetAlbumsResult = await unitOfWork.AlbumRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (resetAlbumsResult.IsFailure) + return resetAlbumsResult.Errors; + return await unitOfWork.TrackRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resets the artwork enrichment status of all the artists, albums and tracks of the media library identified by . + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose artwork is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetArtworkStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken) + { + return await unitOfWork.MusicArtworkRepository.ResetStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the name of the artist of the provided staged , falling back to a placeholder when the metadata does not provide one. + /// + /// The staged music metadata item whose artist name is retrieved. + /// The name of the artist. + private static string GetArtistName(MusicLibraryScanItemMetadataEntity stagedItem) + { + return string.IsNullOrWhiteSpace(stagedItem.ArtistName) ? UNKNOWN_ARTIST_NAME : stagedItem.ArtistName; + } + + /// + /// Gets the title of the release of the provided staged , falling back to a placeholder when the metadata does not provide one. + /// + /// The staged music metadata item whose release title is retrieved. + /// The title of the release. + private static string GetAlbumTitle(MusicLibraryScanItemMetadataEntity stagedItem) + { + return string.IsNullOrWhiteSpace(stagedItem.ReleaseName) ? UNKNOWN_ALBUM_TITLE : stagedItem.ReleaseName; + } + + /// + /// Creates a new artist entity for the media library identified by . + /// + /// The Id of the media library the artist belongs to. + /// The name of the artist. + /// The MusicBrainz identifier of the artist, read from the tags, if applicable. + /// The created artist entity. + private static ArtistEntity CreateArtistEntity(Guid libraryId, string name, Guid? musicBrainzArtistId) + { + return new ArtistEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + Name = name, + MusicBrainzArtistId = musicBrainzArtistId, + MetadataStatus = MetadataStatus.Pending, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Creates a new album entity for the artist identified by , using the metadata of the provided staged . + /// + /// The Id of the media library the album belongs to. + /// The Id of the artist the album belongs to. + /// The title of the album. + /// The staged music metadata items of the album. + /// The MusicBrainz identifier of the release, read from the tags, if applicable. + /// The MusicBrainz identifier of the release group, read from the tags, if applicable. + /// The MusicBrainz identifier of the release artist, read from the tags, if applicable. + /// The created album entity. + private static AlbumEntity CreateAlbumEntity(Guid libraryId, Guid artistId, string title, IReadOnlyList stagedItems, Guid? musicBrainzReleaseId, Guid? musicBrainzReleaseGroupId, Guid? musicBrainzReleaseArtistId) + { + MusicLibraryScanItemMetadataEntity firstStagedItem = stagedItems[0]; + return new AlbumEntity + { + Id = Guid.NewGuid(), + ArtistId = artistId, + LibraryId = libraryId, + Title = title, + MusicBrainzReleaseId = musicBrainzReleaseId, + MusicBrainzReleaseGroupId = musicBrainzReleaseGroupId, + MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId, + ReleaseTypes = firstStagedItem.ReleaseType is null ? [] : [new AlbumReleaseTypeEntity(firstStagedItem.ReleaseType.Value)], + OriginalReleaseYear = firstStagedItem.ReleaseYear, + MetadataStatus = MetadataStatus.Pending, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Creates a new track entity for the album identified by , using the metadata of the provided staged . + /// + /// The Id of the media library the track belongs to. + /// The Id of the album the track belongs to. + /// The staged music metadata item of the track. + /// The created track entity. + private TrackEntity CreateTrackEntity(Guid libraryId, Guid albumId, MusicLibraryScanItemMetadataEntity stagedItem) + { + return new TrackEntity + { + Id = Guid.NewGuid(), + AlbumId = albumId, + LibraryId = libraryId, + Path = stagedItem.Path, + Title = string.IsNullOrWhiteSpace(stagedItem.TrackTitle) ? _pathService.GetFileNameWithoutExtension(stagedItem.Path) : stagedItem.TrackTitle, + TrackNumber = stagedItem.TrackNumber ?? 0, + DiscNumber = stagedItem.DiscNumber, + DurationInSeconds = stagedItem.DurationInSeconds, + SampleRate = stagedItem.SampleRate, + Channels = stagedItem.Channels, + BitDepth = stagedItem.BitDepth, + AudioCodec = stagedItem.AudioCodec, + Bitrate = stagedItem.Bitrate, + AcoustId = stagedItem.AcoustId, + ReplayGainTrackGain = stagedItem.ReplayGainTrackGain, + ReplayGainTrackPeak = stagedItem.ReplayGainTrackPeak, + ReplayGainAlbumGain = stagedItem.ReplayGainAlbumGain, + ReplayGainAlbumPeak = stagedItem.ReplayGainAlbumPeak, + Moods = [.. stagedItem.Moods.Select(mood => new TrackMoodEntity(mood))], + MusicBrainzRecordingId = stagedItem.MusicBrainzRecordingId, + MusicBrainzTrackId = stagedItem.MusicBrainzTrackId, + MusicBrainzWorkId = stagedItem.MusicBrainzWorkId, + WorkTitle = stagedItem.WorkTitle, + MetadataStatus = MetadataStatus.Pending, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs new file mode 100644 index 00000000..2c631cb0 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs @@ -0,0 +1,601 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Metadata enricher for the media library items of the music media library type, using the metadata providers configured for the media library. +/// The enriched metadata is applied to the artists, their albums and their tracks, and the media contributors discovered while enriching are linked to them. +/// +internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanMetadataEnricher +{ + private const int ENRICHMENT_PAGE_SIZE = 200; // The number of artists that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// The media library type that this metadata enricher supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Music; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating scopes in which services are requested. + /// Injected logger used to report the issues encountered while enriching the metadata. + public MusicMediaLibraryScanMetadataEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Enriches the metadata of the artists, the albums and the tracks of the provided media library, using the metadata providers configured for it. + /// + /// The unique identifier of the media library whose items are enriched. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken) + { + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId); + + // Load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment. + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the providers requiring the web will not be used."); + else + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + + // Get the metadata providers configured for the media library, in their configured order, that support the media library type, + // skipping the providers that require access to the web when the media library does not permit downloading data from the web. + Result> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + throw new InvalidOperationException(getConfigurationsResult.FirstError.Description); + List providers = []; + foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music); + providers.AddRange(configuredProviders); + } + + // Read whether the metadata of the items of the user is aggregated from multiple providers, when fields are missing. + bool shouldAggregateMetadataWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) + { + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the metadata will not be aggregated across providers."); + else + shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; + } + + // When no metadata provider is available, the items must not be marked as failed to enrich, so the enrichment is skipped entirely. + if (providers.Count > 0) + { + Result getArtistsToEnrichCountResult = await unitOfWork.ArtistRepository.GetArtistsNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtistsToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getArtistsToEnrichCountResult.FirstError.Description); + + Result getAlbumsToEnrichCountResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getAlbumsToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getAlbumsToEnrichCountResult.FirstError.Description); + + Result getTracksToEnrichCountResult = await unitOfWork.TrackRepository.GetTracksNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getTracksToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getTracksToEnrichCountResult.FirstError.Description); + + // The progress is measured in items, not artists: an artist is counted together with its albums and its tracks, because enriching a single + // artist can require a large number of metadata provider calls, one for each of its tracks, and would otherwise barely advance the progress. + int totalItemsToEnrich = getArtistsToEnrichCountResult.Value + getAlbumsToEnrichCountResult.Value + getTracksToEnrichCountResult.Value; + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedItemsCount = 0; + + // Reports that a single item (an artist, an album or a track) was processed, publishing the progress at most once per interval. + async Task ReportItemProcessedAsync() + { + int processedItems = Interlocked.Increment(ref processedItemsCount); + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + Result publishItemProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, processedItems, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishItemProgressResult.IsFailure) + throw new InvalidOperationException(publishItemProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + // The media contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only + // created once even when the same person is discovered for many items of the same page. + Dictionary contributorsByNormalizedName = []; + + // Process the artists that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size. + string? lastName = null; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getArtistsPageResult = await unitOfWork.ArtistRepository.GetArtistsNeedingMetadataAsync(libraryId.Value, lastName, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getArtistsPageResult.IsFailure) + throw new InvalidOperationException(getArtistsPageResult.FirstError.Description); + IReadOnlyList artistsPage = getArtistsPageResult.Value; + if (artistsPage.Count == 0) + break; + + foreach (ArtistEntity artistEntity in artistsPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + await EnrichArtistAsync(artistEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork, contributorsByNormalizedName, ReportItemProcessedAsync, cancellationToken).ConfigureAwait(false); + + // Persist each enriched artist as soon as it is done, then detach it, so that an interrupted scan keeps everything it already + // enriched, and the peak memory stays bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + { + // A unique constraint conflict on a shared lookup such as a media contributor can happen when two scans enrich concurrently; + // it must not abort the whole scan, so the artist is left unenriched and retried on the next scan, while the rest proceeds. + if (saveChangesResult.FirstError == Errors.Persistence.UniqueConstraintViolation) + _logger.LogWarning("The enriched metadata of the artist '{ArtistName}' could not be persisted because of a unique constraint conflict; it will be retried on the next scan.", artistEntity.Name); + else + throw new InvalidOperationException(saveChangesResult.FirstError.Description); + } + unitOfWork.ClearTrackedEntities(); + contributorsByNormalizedName.Clear(); + } + + lastName = artistsPage[^1].Name; + } + + // The enrichment finished, force the progress to reach its total, so that an item skipped during an early return cannot leave it incomplete. + Result publishFinalProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, totalItemsToEnrich, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishFinalProgressResult.IsFailure) + throw new InvalidOperationException(publishFinalProgressResult.FirstError.Description); + } + else + _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value); + } + + /// + /// Enriches the metadata of the provided , its albums and its tracks, using the provided metadata providers in their configured order. + /// + /// The artist whose metadata, and the metadata of its albums and tracks, is enriched. + /// The metadata providers, in their configured order. + /// Whether the metadata is aggregated from multiple providers, when fields are missing, or not. + /// The unit of work used to persist the enriched artist. + /// The cache of the media contributors discovered in the current page, keyed by their normalized display name. + /// The callback invoked after each artist, album or track is processed. + /// Cancellation token that can be used to stop the execution. + private async Task EnrichArtistAsync(ArtistEntity artistEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IUnitOfWork unitOfWork, Dictionary contributorsByNormalizedName, Func onItemProcessed, CancellationToken cancellationToken) + { + // Convert the artist aggregate, together with its albums and tracks, to a domain object. + Result getArtistResult = artistEntity.ToDomainEntity(); + if (getArtistResult.IsFailure) + return; + Artist artist = getArtistResult.Value; + + string fallbackPath = artistEntity.Albums.SelectMany(album => album.Tracks).Select(track => track.Path).FirstOrDefault() ?? string.Empty; + + if (artistEntity.MetadataStatus != MetadataStatus.Enriched) + { + ArtistMetadataLookupDto artistLookup = new( + LibraryId: artistEntity.LibraryId, + Path: fallbackPath, + MusicBrainzArtistId: artistEntity.MusicBrainzArtistId, + Name: artistEntity.Name); + ResolvedMetadata? resolvedArtist = await ResolveAndApplyMetadataAsync( + artistLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableArtistMetadata, + (first, second) => MusicMetadataAggregator.Merge(first, second), + async metadata => + { + List contributors = await ResolveContributorsAsync(metadata.Contributors, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); + return metadata.ApplyTo(artist, contributors); + }, _logger, cancellationToken).ConfigureAwait(false); + if (resolvedArtist is null) + artistEntity.MetadataStatus = MetadataStatus.Failed; + else + { + artistEntity.MetadataStatus = MetadataStatus.Enriched; + artistEntity.MetadataProvider = resolvedArtist.ProviderName; + artistEntity.LastMetadataUpdateUtc = DateTime.UtcNow; + } + } + + // An artist is reported as processed even when its own metadata was already enriched, because it is only visited when one of its descendants still needs it. + await onItemProcessed().ConfigureAwait(false); + + foreach (AlbumEntity albumEntity in artistEntity.Albums) + { + Album? album = artist.Albums.FirstOrDefault(candidate => candidate.Id.Value == albumEntity.Id); + if (album is null) + continue; + + // The release the tracks of the album are enriched from: it comes from the tags, or from the release the album was matched to, and it is + // only ever a release whose tracklist corresponds to the local files, so the tracks are never resolved from a different edition. + Guid? albumReleaseId = albumEntity.MusicBrainzReleaseId; + + if (albumEntity.MetadataStatus != MetadataStatus.Enriched) + { + string albumPath = albumEntity.Tracks.Select(track => track.Path).FirstOrDefault() ?? fallbackPath; + AlbumMetadataLookupDto albumLookup = new( + LibraryId: artistEntity.LibraryId, + Path: albumPath, + MusicBrainzReleaseGroupId: albumEntity.MusicBrainzReleaseGroupId, + MusicBrainzReleaseId: albumEntity.MusicBrainzReleaseId, + Title: albumEntity.Title, + ArtistName: artistEntity.Name, + ReleaseYear: albumEntity.OriginalReleaseYear, + TrackCount: albumEntity.Tracks.Count); + ResolvedMetadata? resolvedAlbum = await ResolveAndApplyMetadataAsync( + albumLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableAlbumMetadata, + (first, second) => MusicMetadataAggregator.Merge(first, second), + async metadata => + { + List contributors = await ResolveContributorsAsync(metadata.Contributors, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); + return metadata.ApplyTo(artist, album, contributors); + }, _logger, cancellationToken).ConfigureAwait(false); + if (resolvedAlbum is null) + albumEntity.MetadataStatus = MetadataStatus.Failed; + else + { + albumReleaseId = resolvedAlbum.Metadata.MusicBrainzReleaseId ?? albumReleaseId; + albumEntity.MetadataStatus = MetadataStatus.Enriched; + albumEntity.MetadataProvider = resolvedAlbum.ProviderName; + albumEntity.LastMetadataUpdateUtc = DateTime.UtcNow; + } + await onItemProcessed().ConfigureAwait(false); + } + + foreach (TrackEntity trackEntity in albumEntity.Tracks) + { + if (trackEntity.MetadataStatus == MetadataStatus.Enriched) + continue; + Track? track = album.Tracks.FirstOrDefault(candidate => candidate.Id.Value == trackEntity.Id); + if (track is null) + continue; + + TrackMetadataLookupDto trackLookup = new( + LibraryId: artistEntity.LibraryId, + Path: trackEntity.Path, + MusicBrainzRecordingId: trackEntity.MusicBrainzRecordingId, + Isrc: trackEntity.Isrcs.Select(isrc => isrc.Value).FirstOrDefault(), + Title: trackEntity.Title, + ArtistName: artistEntity.Name, + ReleaseName: albumEntity.Title, + TrackNumber: trackEntity.TrackNumber, + DurationInSeconds: trackEntity.DurationInSeconds > 0 ? trackEntity.DurationInSeconds : null, + MusicBrainzReleaseId: albumReleaseId, + DiscNumber: trackEntity.DiscNumber, + MusicBrainzWorkId: trackEntity.MusicBrainzWorkId, + WorkTitle: trackEntity.WorkTitle); + ResolvedMetadata? resolvedTrack = await ResolveAndApplyMetadataAsync( + trackLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableAudioMetadata, + (first, second) => MusicMetadataAggregator.Merge(first, second), + async metadata => + { + List contributors = await ResolveContributorsAsync(metadata.Contributors, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); + return metadata.ApplyTo(artist, album, track, contributors); + }, _logger, cancellationToken).ConfigureAwait(false); + if (resolvedTrack is null) + trackEntity.MetadataStatus = MetadataStatus.Failed; + else + { + trackEntity.MetadataStatus = MetadataStatus.Enriched; + trackEntity.MetadataProvider = resolvedTrack.ProviderName; + trackEntity.LastMetadataUpdateUtc = DateTime.UtcNow; + } + await onItemProcessed().ConfigureAwait(false); + } + } + + // Rebuild the repository entity graph from the enriched domain aggregate, carrying over the enrichment tracking columns of the tracked entities. + ArtistEntity enrichedEntity = artist.ToRepositoryEntity(); + CopyEnrichmentTracking(enrichedEntity, artistEntity); + + Result updateResult = await unitOfWork.ArtistRepository.UpdateAsync(enrichedEntity, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + throw new InvalidOperationException(updateResult.FirstError.Description); + } + + /// + /// Resolves the metadata of the provided lookup and applies it to the media item, either from the first provider whose metadata is usable and applies successfully, + /// or, when aggregation is enabled, from the merged metadata of every usable provider. + /// + /// The type of the lookup the metadata providers must accept. + /// The type of the metadata returned by the metadata providers. + /// The lookup describing the media item. + /// The metadata providers, in their configured order. + /// Whether the metadata of every usable provider is merged, or only the first one is used. + /// The predicate that determines whether a metadata result is usable. + /// The function that merges two metadata results. + /// The function that applies a metadata result to the media item. + /// The logger used to report the metadata providers that fail. + /// Cancellation token that can be used to stop the execution. + /// The applied metadata and the name of the provider, or the providers, that supplied it, or when no provider returned applicable metadata. + private static async Task?> ResolveAndApplyMetadataAsync(MetadataLookupDto lookup, IReadOnlyList metadataProviders, bool shouldAggregate, Func isUsable, Func merge, Func>> applyAsync, ILogger logger, CancellationToken cancellationToken) + where TLookup : MetadataLookupDto + where TMetadata : MetadataDto + { + if (shouldAggregate) + return await ResolveAggregatedAndApplyAsync(lookup, metadataProviders, isUsable, merge, applyAsync, logger, cancellationToken).ConfigureAwait(false); + return await ResolveFirstAndApplyAsync(lookup, metadataProviders, isUsable, applyAsync, logger, cancellationToken).ConfigureAwait(false); + } + + /// + /// Tries the providers in configured order, applying the metadata of the first one that is usable and applies successfully, without ever querying the providers that come after it. + /// + /// The type of the lookup the metadata providers must accept. + /// The type of the metadata returned by the metadata providers. + /// The lookup describing the media item. + /// The metadata providers, in their configured order. + /// The predicate that determines whether a metadata result is usable. + /// The function that applies a metadata result to the media item. + /// The logger used to report the metadata providers that fail. + /// Cancellation token that can be used to stop the execution. + /// The applied metadata and the name of the provider that supplied it, or when no provider returned applicable metadata. + private static async Task?> ResolveFirstAndApplyAsync(MetadataLookupDto lookup, IReadOnlyList metadataProviders, Func isUsable, Func>> applyAsync, ILogger logger, CancellationToken cancellationToken) + where TLookup : MetadataLookupDto + where TMetadata : MetadataDto + { + foreach (IMetadataProvider metadataProvider in metadataProviders) + { + if (metadataProvider.LookupType != typeof(TLookup)) + continue; + + try + { + MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false); + if (metadataResult is not TMetadata metadata || !isUsable(metadata)) + continue; + + // The metadata is applied while the provider is being tried, so that a provider whose metadata cannot be applied does not stop the enrichment and the next one is tried instead. + Result applyResult = await applyAsync(metadata).ConfigureAwait(false); + if (applyResult.IsFailure) + continue; + return new ResolvedMetadata(metadata, metadataProvider.Name); + } + catch (Exception exception) + { + // A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. + logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup); + } + } + return null; + } + + /// + /// Queries every provider, merges the metadata of the usable ones, and applies the merged metadata once. + /// + /// The type of the lookup the metadata providers must accept. + /// The type of the metadata returned by the metadata providers. + /// The lookup describing the media item. + /// The metadata providers, in their configured order. + /// The predicate that determines whether a metadata result is usable. + /// The function that merges two metadata results. + /// The function that applies a metadata result to the media item. + /// The logger used to report the metadata providers that fail. + /// Cancellation token that can be used to stop the execution. + /// The applied merged metadata and the names of the providers that supplied it, or when no provider returned applicable metadata. + private static async Task?> ResolveAggregatedAndApplyAsync(MetadataLookupDto lookup, IReadOnlyList metadataProviders, Func isUsable, Func merge, Func>> applyAsync, ILogger logger, CancellationToken cancellationToken) + where TLookup : MetadataLookupDto + where TMetadata : MetadataDto + { + TMetadata? mergedMetadata = default; + List providerNames = []; + foreach (IMetadataProvider metadataProvider in metadataProviders) + { + if (metadataProvider.LookupType != typeof(TLookup)) + continue; + + try + { + MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false); + if (metadataResult is not TMetadata metadata || !isUsable(metadata)) + continue; + + mergedMetadata = mergedMetadata is null ? metadata : merge(mergedMetadata, metadata); + providerNames.Add(metadataProvider.Name); + } + catch (Exception exception) + { + // A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. + logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup); + } + } + + if (mergedMetadata is null) + return null; + + Result applyResult = await applyAsync(mergedMetadata).ConfigureAwait(false); + if (applyResult.IsFailure) + return null; + return new ResolvedMetadata(mergedMetadata, string.Join(", ", providerNames.Distinct(StringComparer.Ordinal))); + } + + /// + /// Finds the media contributor with the name of the provided , or creates it, caching it by its normalized display name + /// so that a contributor is only created once even when the same person is discovered for many items of the same page. + /// + /// The metadata contributors to resolve. + /// The repository used to persist the media contributors discovered while enriching. + /// The cache of the media contributors discovered in the current page, keyed by their normalized display name. + /// Cancellation token that can be used to stop the execution. + /// The resolved domain media contributors, already carrying their persisted identifiers. + private static async Task> ResolveContributorsAsync(IReadOnlyCollection? contributors, IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, CancellationToken cancellationToken) + { + List resolvedContributors = []; + foreach (MediaContributorDto contributor in contributors ?? []) + { + if (contributor.Name?.DisplayName is null) + continue; + + string displayName = contributor.Name.DisplayName; + string normalizedDisplayName = displayName.ToLowerInvariant(); + if (!contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? contributorEntity)) + { + Result getContributorResult = await mediaContributorRepository.FindOrCreateByDisplayNameAsync(displayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false); + if (getContributorResult.IsFailure) + throw new InvalidOperationException(getContributorResult.FirstError.Description); + contributorEntity = getContributorResult.Value; + contributorsByNormalizedName[normalizedDisplayName] = contributorEntity; + } + + MediaContributorRole role = contributor.Role ?? MediaContributorRole.Performer; + if (resolvedContributors.Any(resolved => resolved.ContributorId.Value == contributorEntity.Id && resolved.Role == role)) + continue; + + Result domainContributorResult = MusicMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role); + if (domainContributorResult.IsFailure) + continue; + resolvedContributors.Add(domainContributorResult.Value); + } + return resolvedContributors; + } + + /// + /// Copies the metadata enrichment tracking columns of the tracked artist, albums and tracks onto the rebuilt repository entity graph. + /// + /// The rebuilt repository entity graph that receives the tracking columns. + /// The tracked repository entity graph that carries the tracking columns. + private static void CopyEnrichmentTracking(ArtistEntity target, ArtistEntity source) + { + target.MetadataStatus = source.MetadataStatus; + target.MetadataProvider = source.MetadataProvider; + target.LastMetadataUpdateUtc = source.LastMetadataUpdateUtc; + foreach (AlbumEntity targetAlbum in target.Albums) + { + AlbumEntity? sourceAlbum = source.Albums.FirstOrDefault(album => album.Id == targetAlbum.Id); + if (sourceAlbum is null) + continue; + targetAlbum.MetadataStatus = sourceAlbum.MetadataStatus; + targetAlbum.MetadataProvider = sourceAlbum.MetadataProvider; + targetAlbum.LastMetadataUpdateUtc = sourceAlbum.LastMetadataUpdateUtc; + foreach (TrackEntity targetTrack in targetAlbum.Tracks) + { + TrackEntity? sourceTrack = sourceAlbum.Tracks.FirstOrDefault(track => track.Id == targetTrack.Id); + if (sourceTrack is null) + continue; + targetTrack.MetadataStatus = sourceTrack.MetadataStatus; + targetTrack.MetadataProvider = sourceTrack.MetadataProvider; + targetTrack.LastMetadataUpdateUtc = sourceTrack.LastMetadataUpdateUtc; + } + } + } + + /// + /// Determines whether the provided artist metadata is usable, meaning it has a name. + /// + /// The metadata to validate. + /// when the metadata is usable, otherwise . + private static bool IsUsableArtistMetadata(ArtistMetadataDto metadata) + { + return !string.IsNullOrWhiteSpace(metadata.Name); + } + + /// + /// Determines whether the provided album metadata is usable, meaning it has a title. + /// + /// The metadata to validate. + /// when the metadata is usable, otherwise . + private static bool IsUsableAlbumMetadata(AlbumMetadataDto metadata) + { + return !string.IsNullOrWhiteSpace(metadata.Title); + } + + /// + /// Determines whether the provided audio metadata is usable, meaning it has a title. + /// + /// The metadata to validate. + /// when the metadata is usable, otherwise . + private static bool IsUsableAudioMetadata(AudioMetadataDto metadata) + { + return !string.IsNullOrWhiteSpace(metadata.Title); + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The unique identifier of the media library being scanned. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } + + /// + /// The metadata resolved for a media library item, along with the provider, or providers, that supplied it. + /// + /// The type of the resolved metadata. + /// The resolved metadata of the item. + /// The name of the provider, or the providers, that supplied the metadata. + private sealed record ResolvedMetadata(TMetadata Metadata, string ProviderName) where TMetadata : MetadataDto; +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs new file mode 100644 index 00000000..f96b6d29 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs @@ -0,0 +1,553 @@ +#region ========================================================================= USING ===================================================================================== +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.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Media library scan job for extracting the metadata of the discovered music file system items. +/// +internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMetadataExtractionJob +{ + private const int EXTRACTION_BATCH_SIZE = 1000; // The number of extracted metadata items that are written to the staging results in a single batch, keeping the peak memory bounded regardless of the library size. + private static readonly TagLib.TagTypes[] s_extendedTagContainerTypes = [TagLib.TagTypes.Xiph, TagLib.TagTypes.Id3v2, TagLib.TagTypes.Apple, TagLib.TagTypes.Ape]; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + /// + /// Injected service for logging. + public MusicMetadataExtractionJob(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The id of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). + int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); + // Only execute this job's payload when it has no parents, or when all the parents finished their execution. + if (Parents.Count == 0 || parentsCompleted == Parents.Count) + { + // This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // file system processing that takes time, and would block the processing of scan jobs in the in-memory queue. + await Task.Run(async () => + { + Status = LibraryScanJobStatus.Running; + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // Get the library from the repository, both to verify that it exists and to know its content locations. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) + throw new InvalidOperationException(domainLibraryResult.FirstError.Description); + + // The library always carries a path template: the one configured by the user, or the ideal structure of the library type as its default. + ILibraryPathTemplateService pathTemplateService = asyncServiceScope.ServiceProvider.GetService()!; + IPathService pathService = asyncServiceScope.ServiceProvider.GetService()!; + Result pathTemplateResult = pathTemplateService.ResolveTemplate(domainLibraryResult.Value.LibraryType, domainLibraryResult.Value.PathTemplate.Parts); + if (pathTemplateResult.IsFailure) + throw new InvalidOperationException(pathTemplateResult.FirstError.Description); + LibraryPathTemplate pathTemplate = pathTemplateResult.Value; + + // The metadata is extracted only for the files that are new or changed, since the unchanged ones already have their materialized items. + Result> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getPathsResult.IsFailure) + throw new InvalidOperationException(getPathsResult.FirstError.Description); + IReadOnlyList paths = getPathsResult.Value; + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, paths.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1); + DateTime lastHeartbeat = DateTime.UtcNow; + int processedItems = 0; + + List metadataBatch = []; + foreach (string path in paths) + { + cancellationToken.ThrowIfCancellationRequested(); + + metadataBatch.Add(ExtractMetadata(path, domainLibraryResult.Value.ContentLocations, domainLibraryResult.Value.LibraryType, pathTemplate, pathTemplateService, pathService)); + if (metadataBatch.Count >= EXTRACTION_BATCH_SIZE) + { + Result insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false); + if (insertBatchResult.IsFailure) + throw new InvalidOperationException(insertBatchResult.FirstError.Description); + Result saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveBatchResult.IsFailure) + throw new InvalidOperationException(saveBatchResult.FirstError.Description); + metadataBatch.Clear(); + unitOfWork.ClearTrackedEntities(); + } + processedItems++; + + // Increment the number of processed elements progress in a high-frequency counter with low overhead check. + DateTime now = DateTime.UtcNow; + if (now - lastHeartbeat >= heartbeatInterval) + { + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, processedItems, paths.Count, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastHeartbeat = now; + } + } + + // Flush any remaining extracted metadata items that did not reach the batch size. + if (metadataBatch.Count > 0) + { + Result insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false); + if (insertBatchResult.IsFailure) + throw new InvalidOperationException(insertBatchResult.FirstError.Description); + Result saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveBatchResult.IsFailure) + throw new InvalidOperationException(saveBatchResult.FirstError.Description); + } + + // This job finished, increment the number of processed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + Status = LibraryScanJobStatus.Completed; + + // Call each linked child with the obtained payload. + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Extracts the metadata of the music file stored at . + /// + /// The file system path of the music file whose metadata is extracted. + /// The content locations of the media library the music file belongs to. + /// The type of the media library the music file belongs to. + /// The template describing the structure of the media library on disk. + /// The service used to derive the metadata from the path of the music file. + /// The service used to determine the path separator and whether the file is inside the content locations of the media library. + /// The staged music metadata item. + private MusicLibraryScanItemMetadataEntity ExtractMetadata(string path, IReadOnlyCollection contentLocations, LibraryType libraryType, LibraryPathTemplate pathTemplate, ILibraryPathTemplateService pathTemplateService, IPathService pathService) + { + string relativePath = GetRelativePath(path, contentLocations, pathService); + Result> pathMetadataResult = pathTemplateService.Parse(libraryType, pathTemplate, relativePath, pathService.PathSeparator); + + string? artistName = null; + MusicReleaseType? releaseType = null; + int? releaseYear = null; + string? releaseName = null; + int? trackNumber = null; + int? discNumber = null; + string? trackTitle = null; + Guid? musicBrainzArtistId = null; + Guid? musicBrainzReleaseArtistId = null; + Guid? musicBrainzReleaseGroupId = null; + Guid? musicBrainzReleaseId = null; + Guid? musicBrainzRecordingId = null; + Guid? musicBrainzTrackId = null; + Guid? musicBrainzWorkId = null; + string? workTitle = null; + + if (pathMetadataResult.IsSuccess && pathMetadataResult.Value.HasValue) + { + MusicLibraryPathMetadata pathMetadata = MusicLibraryPathMetadata.FromParsedLibraryPath(pathMetadataResult.Value.Value); + if (pathMetadata.ArtistName.HasValue) + artistName = pathMetadata.ArtistName.Value; + if (pathMetadata.ReleaseType.HasValue) + releaseType = pathMetadata.ReleaseType.Value; + if (pathMetadata.ReleaseYear.HasValue) + releaseYear = pathMetadata.ReleaseYear.Value; + if (pathMetadata.ReleaseName.HasValue) + releaseName = pathMetadata.ReleaseName.Value; + if (pathMetadata.TrackNumber.HasValue) + trackNumber = pathMetadata.TrackNumber.Value; + if (pathMetadata.DiscNumber.HasValue) + discNumber = pathMetadata.DiscNumber.Value; + if (pathMetadata.TrackTitle.HasValue) + trackTitle = pathMetadata.TrackTitle.Value; + } + + int durationInSeconds = 0; + int sampleRate = 0; + int channels = 0; + int? bitDepth = null; + string? audioCodec = null; + int? bitrate = null; + string? acoustId = null; + decimal? replayGainTrackGain = null; + decimal? replayGainTrackPeak = null; + decimal? replayGainAlbumGain = null; + decimal? replayGainAlbumPeak = null; + List moods = []; + + try + { + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + TagLib.Tag tag = tagFile.Tag; + if (!string.IsNullOrWhiteSpace(tag.Title)) + trackTitle = tag.Title; + if (!string.IsNullOrWhiteSpace(tag.Album)) + releaseName = tag.Album; + // The album artist is preferred over the track artist, because it is the artist the release belongs to. + string? tagArtist = !string.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstAlbumArtist : tag.FirstPerformer; + if (!string.IsNullOrWhiteSpace(tagArtist)) + artistName = tagArtist; + if (tag.Track > 0) + trackNumber = (int)tag.Track; + if (tag.Disc > 0) + discNumber = (int)tag.Disc; + if (tag.Year > 0) + releaseYear = (int)tag.Year; + + TagLib.Properties audioProperties = tagFile.Properties; + durationInSeconds = (int)audioProperties.Duration.TotalSeconds; + sampleRate = audioProperties.AudioSampleRate; + channels = audioProperties.AudioChannels; + if (audioProperties.BitsPerSample > 0) + bitDepth = audioProperties.BitsPerSample; + if (audioProperties.AudioBitrate > 0) + bitrate = audioProperties.AudioBitrate; + if (!string.IsNullOrWhiteSpace(audioProperties.Description)) + audioCodec = audioProperties.Description; + + // The text frames of the ID3v2 tag are read once for the whole file, so that the extended tag lookups below do not walk all the frames + // of the tag again for every key. + IReadOnlyDictionary id3v2ExtendedFields = GetId3v2ExtendedFields(tagFile); + + // The MusicBrainz identifiers written by taggers like Picard are read here, so that the enrichment can look the items up directly, + // instead of guessing them through searches. The work identifier and title are not exposed as properties by the tagging library, so + // they are read from the extended tags of the container, and they only serve as a fallback for recordings that MusicBrainz leaves unlinked to a work. + musicBrainzArtistId = ParseGuid(tag.MusicBrainzArtistId); + musicBrainzReleaseArtistId = ParseGuid(tag.MusicBrainzReleaseArtistId); + musicBrainzReleaseGroupId = ParseGuid(tag.MusicBrainzReleaseGroupId); + musicBrainzReleaseId = ParseGuid(tag.MusicBrainzReleaseId); + musicBrainzRecordingId = ParseGuid(tag.MusicBrainzTrackId); + musicBrainzTrackId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")); + musicBrainzWorkId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID")); + string? extendedWorkTitle = GetExtendedField(tagFile, id3v2ExtendedFields, "WORK", "MUSICBRAINZ_WORK"); + if (!string.IsNullOrWhiteSpace(extendedWorkTitle)) + workTitle = extendedWorkTitle; + + // The AcoustID, the moods and the ReplayGain values written by taggers like Picard are read here as well. The moods can be a single + // slash separated value or several distinct values, depending on the container, so all of them are read and split before being de-duplicated. + acoustId = GetExtendedField(tagFile, id3v2ExtendedFields, "Acoustid Id", "ACOUSTID_ID"); + moods = [.. GetExtendedFields(tagFile, id3v2ExtendedFields, "mood", "MOOD", "MOODS") + .SelectMany(mood => mood.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + .Where(mood => !string.IsNullOrWhiteSpace(mood)) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + replayGainTrackGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_GAIN", "replaygain_track_gain")); + replayGainTrackPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_PEAK", "replaygain_track_peak")); + replayGainAlbumGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_GAIN", "replaygain_album_gain")); + replayGainAlbumPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_PEAK", "replaygain_album_peak")); + } + } + catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException) + { + // A music file whose tags cannot be read still contributes the metadata derived from its path, but the failure is logged, so that a + // systematic tagging failure of a whole library does not silently degrade every file to path only metadata. + _logger.LogWarning(exception, "Failed to read the embedded tags of the music file '{Path}'. Its metadata will be derived from the path only.", path); + } + + if (string.IsNullOrWhiteSpace(trackTitle)) + trackTitle = pathService.GetFileNameWithoutExtension(path); + + return new MusicLibraryScanItemMetadataEntity + { + Id = Guid.NewGuid(), + LibraryScanId = ScanId.Value, + LibraryId = LibraryId.Value, + Path = path, + ArtistName = artistName, + ReleaseType = releaseType, + ReleaseYear = releaseYear, + ReleaseName = releaseName, + TrackTitle = trackTitle, + TrackNumber = trackNumber, + DiscNumber = discNumber, + DurationInSeconds = durationInSeconds, + SampleRate = sampleRate, + Channels = channels, + BitDepth = bitDepth, + AudioCodec = audioCodec, + Bitrate = bitrate, + AcoustId = acoustId, + ReplayGainTrackGain = replayGainTrackGain, + ReplayGainTrackPeak = replayGainTrackPeak, + ReplayGainAlbumGain = replayGainAlbumGain, + ReplayGainAlbumPeak = replayGainAlbumPeak, + Moods = moods, + MusicBrainzArtistId = musicBrainzArtistId, + MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId, + MusicBrainzReleaseGroupId = musicBrainzReleaseGroupId, + MusicBrainzReleaseId = musicBrainzReleaseId, + MusicBrainzRecordingId = musicBrainzRecordingId, + MusicBrainzTrackId = musicBrainzTrackId, + MusicBrainzWorkId = musicBrainzWorkId, + WorkTitle = workTitle + }; + } + + /// + /// Parses the provided tag as a globally unique identifier. + /// + /// The tag value to parse. + /// The parsed identifier, or when the value is missing or malformed. + private static Guid? ParseGuid(string? value) + { + return Guid.TryParse(value, out Guid parsedValue) ? parsedValue : null; + } + + /// + /// Reads the text frames of the ID3v2 tag of the provided once, keyed by their description and compared + /// case-insensitively, so that every extended tag lookup of the file reuses the same enumeration instead of walking all the frames again. + /// + /// The file whose ID3v2 text frames are read. + /// The text values of the ID3v2 frames, keyed by their description, or an empty dictionary when the file has no ID3v2 tag. + private static Dictionary GetId3v2ExtendedFields(TagLib.File tagFile) + { + Dictionary fields = new(StringComparer.OrdinalIgnoreCase); + if (tagFile.GetTag(TagLib.TagTypes.Id3v2) is not TagLib.Id3v2.Tag id3v2Tag) + return fields; + + // Only the first frame of a given description is kept, so a description that appears more than once always resolves to its first occurrence. + foreach (TagLib.Id3v2.Frame frame in id3v2Tag.GetFrames()) + if (frame is TagLib.Id3v2.UserTextInformationFrame userTextViewFrame + && !string.IsNullOrEmpty(userTextViewFrame.Description) + && !fields.ContainsKey(userTextViewFrame.Description)) + fields[userTextViewFrame.Description] = userTextViewFrame.Text; + return fields; + } + + /// + /// Reads an extended tag that the tagging library does not expose as a property, from whichever container tag of the file carries it. + /// + /// The file whose extended tags are read. + /// The text frames of the ID3v2 tag of the file, read once for the whole file. + /// The candidate names of the extended tag to read, in the order they are tried. + /// The first non-empty value found, or when the file carries none of the provided tags. + private static string? GetExtendedField(TagLib.File tagFile, IReadOnlyDictionary id3v2ExtendedFields, params string[] keys) + { + foreach (TagLib.TagTypes tagType in s_extendedTagContainerTypes) + { + // The frames of the ID3v2 tag were read once for the whole file, so they are looked up instead of being enumerated again for every key. + if (tagType == TagLib.TagTypes.Id3v2) + { + foreach (string key in keys) + if (id3v2ExtendedFields.TryGetValue(key, out string[]? id3v2Values) && id3v2Values.Length > 0 && !string.IsNullOrWhiteSpace(id3v2Values[0])) + return id3v2Values[0]; + continue; + } + + TagLib.Tag? tag = tagFile.GetTag(tagType); + if (tag is null) + continue; + + foreach (string key in keys) + { + string? value = GetExtendedFieldFromTag(tag, key); + if (!string.IsNullOrWhiteSpace(value)) + return value; + } + } + return null; + } + + /// + /// Reads an extended tag with the provided from the provided , according to its container format. + /// + /// The container tag whose extended tags are read. + /// The name of the extended tag to read. + /// The value of the extended tag, or when the tag does not carry it. + private static string? GetExtendedFieldFromTag(TagLib.Tag tag, string key) + { + switch (tag) + { + case TagLib.Ogg.XiphComment xiphComment: + string[] xiphValues = xiphComment.GetField(key); + return xiphValues.Length > 0 ? xiphValues[0] : null; + case TagLib.Mpeg4.AppleTag appleTag: + return appleTag.GetDashBox("com.apple.iTunes", key); + case TagLib.Ape.Tag apeTag: + if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem) + { + string[] apeValues = apeItem.ToStringArray(); + return apeValues.Length > 0 ? apeValues[0] : null; + } + return null; + default: + return null; + } + } + + /// + /// Reads every value of an extended tag that the tagging library does not expose as a property, from whichever container tag of the file carries it. + /// + /// The file whose extended tags are read. + /// The text frames of the ID3v2 tag of the file, read once for the whole file. + /// The candidate names of the extended tag to read, in the order they are tried. + /// Every non-empty value found, or an empty list when the file carries none of the provided tags. + private static List GetExtendedFields(TagLib.File tagFile, IReadOnlyDictionary id3v2ExtendedFields, params string[] keys) + { + List values = []; + foreach (TagLib.TagTypes tagType in s_extendedTagContainerTypes) + { + // The frames of the ID3v2 tag were read once for the whole file, so they are looked up instead of being enumerated again for every key. + if (tagType == TagLib.TagTypes.Id3v2) + { + foreach (string key in keys) + if (id3v2ExtendedFields.TryGetValue(key, out string[]? id3v2Values)) + values.AddRange(id3v2Values.Where(value => !string.IsNullOrWhiteSpace(value))); + continue; + } + + TagLib.Tag? tag = tagFile.GetTag(tagType); + if (tag is null) + continue; + + foreach (string key in keys) + values.AddRange(GetExtendedFieldsFromTag(tag, key).Where(value => !string.IsNullOrWhiteSpace(value))); + } + return values; + } + + /// + /// Reads every value of an extended tag with the provided from the provided , according to its container format. + /// + /// The container tag whose extended tags are read. + /// The name of the extended tag to read. + /// Every value of the extended tag, or an empty list when the tag does not carry it. + private static List GetExtendedFieldsFromTag(TagLib.Tag tag, string key) + { + switch (tag) + { + case TagLib.Ogg.XiphComment xiphComment: + return [.. xiphComment.GetField(key)]; + case TagLib.Mpeg4.AppleTag appleTag: + string? value = appleTag.GetDashBox("com.apple.iTunes", key); + return string.IsNullOrWhiteSpace(value) ? [] : [.. value.Split('\0', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)]; + case TagLib.Ape.Tag apeTag: + if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem) + return [.. apeItem.ToStringArray()]; + return []; + default: + return []; + } + } + + /// + /// Parses a ReplayGain value, optionally suffixed with its unit, into a decimal. + /// + /// The value to parse. + /// The parsed decimal, or when the value is missing or malformed. + private static decimal? ParseDecimal(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + + string cleaned = value.Replace("dB", string.Empty, StringComparison.OrdinalIgnoreCase).Trim(); + return decimal.TryParse(cleaned, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal parsed) ? parsed : null; + } + + /// + /// Gets the path of the music file stored at , relative to the content location of the media library it belongs to. + /// + /// The absolute file system path of the music file. + /// The content locations of the media library the music file belongs to. + /// The service used to determine whether the file is inside a content location of the media library. + /// The path of the music file, relative to its content location, or the file name when no content location contains it. + private static string GetRelativePath(string path, IReadOnlyCollection contentLocations, IPathService pathService) + { + foreach (FileSystemPathId contentLocation in contentLocations) + { + if (pathService.IsPathWithin(path, contentLocation.Path)) + { + string relativePath = path[contentLocation.Path.Length..].TrimStart('\\', '/'); + if (relativePath.Length > 0) + return relativePath; + } + } + return pathService.GetFileName(path); + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ExtractingMetadata"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs new file mode 100644 index 00000000..065c32f1 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Interface defining the artwork enrichment of the media library items of a specific media library type. +/// +internal interface IMediaLibraryScanArtworkEnricher +{ + /// + /// The media library type that this artwork enricher supports. + /// + LibraryType SupportedLibraryType { get; } + + /// + /// Resolves the artwork of the media library items of the provided media library, using the artwork providers configured for it. + /// + /// The unique identifier of the media library whose artwork is resolved. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanItemMaterializer.cs new file mode 100644 index 00000000..2938eec8 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanItemMaterializer.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Interface defining the materialization of the media library items of a specific media library type from the results of a media library scan. +/// +internal interface IMediaLibraryScanItemMaterializer +{ + /// + /// The media library type that this materializer supports. + /// + LibraryType SupportedLibraryType { get; } + + /// + /// Resets the enrichment state of the media library items stored at the provided , so that they are re-enriched, because their content changed since the last scan. + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose items are reset. + /// The file system paths of the media library items whose enrichment state is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetEnrichmentStateForChangedPathsAsync(IUnitOfWork unitOfWork, Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken); + + /// + /// Materializes the media library items of the media library from the paths of the media library scan snapshot. + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose items are materialized. + /// The Id of the media library scan whose results are materialized. + /// The file system paths of the media library scan snapshot. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList paths, CancellationToken cancellationToken); + + /// + /// Resets the metadata enrichment status of all the media library items of the media library identified by . + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose items are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetMetadataStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken); + + /// + /// Resets the artwork enrichment status of all the media library items of the media library identified by . + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose artwork is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetArtworkStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanMetadataEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanMetadataEnricher.cs new file mode 100644 index 00000000..886f2160 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanMetadataEnricher.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Interface defining the metadata enrichment of the media library items of a specific media library type. +/// +internal interface IMediaLibraryScanMetadataEnricher +{ + /// + /// The media library type that this metadata enricher supports. + /// + LibraryType SupportedLibraryType { get; } + + /// + /// Enriches the metadata of the media library items of the provided media library, using the metadata providers configured for it. + /// + /// The unique identifier of the media library whose items are enriched. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs index 31d7f468..64b5506a 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs @@ -1,25 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Security; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using System; -using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -29,13 +18,11 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// /// Media library scan job for resolving the artwork of the media library items, using the artwork providers configured for the media library. -/// The artwork is tracked per book, per type and ordinal, so that a change of one artwork does not require the others to be re-fetched. +/// The enrichment itself is delegated to the artwork enricher of the media library type. /// internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob { - private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly ILogger _logger; /// /// Initializes a new instance of the class. @@ -44,11 +31,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob /// Injected factory for creating scopes in which services are requested. /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. /// - /// Injected logger used to report the issues encountered while resolving the artwork. - public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger logger) + public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; - _logger = logger; } /// @@ -79,113 +64,22 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines - // whether the providers that require access to the web are used during the enrichment. - string libraryName = string.Empty; - bool canDownloadMetadataFromWeb = false; - if (unitOfWork.LibraryRepository is not null) - { - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used."); - else - { - libraryName = getLibraryResult.Value.Title; - canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; - } - } + // Load the media library, whose type determines the artwork enricher to use. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryType libraryType = getLibraryResult.Value.LibraryType; - // Get the artwork providers configured for the media library, in their configured order, that support the media library type. - // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding. - List artworkProviders = []; - if (unitOfWork.ArtworkProviderConfigurationRepository is not null) - { - Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getArtworkConfigurationsResult.IsFailure) - _logger.LogWarning("Failed to read the artwork provider configurations."); - else - { - foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) - { - List configuredProviders = [.. asyncServiceScope.ServiceProvider - .GetKeyedServices(configuration.PluginId) - .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) - && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; - if (configuredProviders.Count == 0) - _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); - artworkProviders.AddRange(configuredProviders); - } - } - } + IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); + if (artworkEnricher is null) + throw new InvalidOperationException($"No artwork enricher exists for media library type '{libraryType}'."); - // When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely. - if (artworkProviders.Count > 0) - { - IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); - IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + await artworkEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false); - Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getBooksToEnrichCountResult.IsFailure) - throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); - int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - - // Set the initial progress of the scan job. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - int processedBooksCount = 0; - - // Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size. - string? lastPath = null; - while (true) - { - cancellationToken.ThrowIfCancellationRequested(); - - Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); - if (getBooksPageResult.IsFailure) - throw new InvalidOperationException(getBooksPageResult.FirstError.Description); - IReadOnlyList booksPage = getBooksPageResult.Value; - if (booksPage.Count == 0) - break; - - // Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory. - Result> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false); - if (getAuthorsResult.IsFailure) - throw new InvalidOperationException(getAuthorsResult.FirstError.Description); - - foreach (BookEntity bookEntity in booksPage) - { - cancellationToken.ThrowIfCancellationRequested(); - - await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false); - - // Check if enough time has passed since the last update. - DateTime now = DateTime.UtcNow; - if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) - { - // Increment the number of processed elements progress. - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - lastUpdateTime = now; - } - } - - // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. - Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - throw new InvalidOperationException(saveChangesResult.FirstError.Description); - unitOfWork.ClearTrackedEntities(); - - lastPath = booksPage[^1].Path; - } - } - else - _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", LibraryId.Value); - + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) @@ -208,199 +102,4 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); } } - - /// - /// Resolves the cover artwork of the provided from the , in their configured order, - /// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book. - /// - /// The book whose artwork is resolved. - /// The artwork providers, in their configured order. - /// The service used to store the artwork of the book. - /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. - /// The name of the media library the book belongs to. - /// The display names of the authors of the books of the current page, keyed by the Id of the book. - /// Cancellation token that can be used to stop the execution. - private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary authorsDisplayNamesByBookId, CancellationToken cancellationToken) - { - // When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped. - if (bookArtworkService is null || artworkProviders.Count == 0) - return; - - ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false); - if (resolvedArtwork is null) - { - // No artwork provider returned usable artwork, so the cover artwork of the book is marked as failed to resolve. - BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); - if (coverArtwork is null) - bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); - else - { - coverArtwork.Status = ArtworkStatus.Failed; - coverArtwork.UpdatedOnUtc = DateTime.UtcNow; - coverArtwork.UpdatedBy = Guid.NewGuid(); - } - return; - } - - BookArtworkEntity? existingCoverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); - - // When the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one - // is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it. - ulong contentHash = 0; - bool shouldStoreArtwork = true; - if (!string.IsNullOrWhiteSpace(resolvedArtwork.Artwork.LocalPath)) - { - contentHash = fileHashService.ComputeFileHash(resolvedArtwork.Artwork.LocalPath); - shouldStoreArtwork = existingCoverArtwork is null || contentHash != existingCoverArtwork.ContentHash; - } - - if (shouldStoreArtwork) - { - string authorName = authorsDisplayNamesByBookId.TryGetValue(bookEntity.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; - Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false); - if (saveArtworkResult.IsFailure) - { - // A failing artwork storage must not prevent the book from being tracked as failed to resolve. - if (existingCoverArtwork is null) - bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); - else - { - existingCoverArtwork.Status = ArtworkStatus.Failed; - existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedBy = Guid.NewGuid(); - } - return; - } - - // For remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one. - if (contentHash == 0) - { - string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\')); - contentHash = fileHashService.ComputeFileHash(storedArtworkPath); - } - - if (existingCoverArtwork is null) - bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); - else - { - existingCoverArtwork.FileName = saveArtworkResult.Value; - existingCoverArtwork.ContentHash = contentHash; - existingCoverArtwork.Status = ArtworkStatus.Enriched; - existingCoverArtwork.Provider = resolvedArtwork.ProviderName; - existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedBy = Guid.NewGuid(); - } - } - else - { - // The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched. - existingCoverArtwork!.Status = ArtworkStatus.Enriched; - existingCoverArtwork.Provider = resolvedArtwork.ProviderName; - existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedBy = Guid.NewGuid(); - } - } - - /// - /// Resolves the artwork of the from the , in their configured order, - /// returning the artwork of the first provider that returns it. - /// - /// The book whose artwork is resolved. - /// The artwork providers, in their configured order. - /// Cancellation token that can be used to stop the execution. - /// The resolved artwork and the provider that supplied it, or when no provider returned usable artwork. - private static async Task ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, CancellationToken cancellationToken) - { - BookMetadataLookupDto artworkLookup = new( - LibraryId: bookEntity.LibraryId, - Path: bookEntity.Path, - Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, - OpenLibraryId: bookEntity.OpenLibraryId, - Title: bookEntity.Title, - Author: null, - LanguageCode: bookEntity.LanguageCode - ); - - foreach (IArtworkProvider provider in artworkProviders) - { - ArtworkDto? artwork = null; - try - { - artwork = await provider.GetArtworkAsync(artworkLookup, cancellationToken).ConfigureAwait(false); - } - catch (Exception) - { - // A failing artwork provider must not prevent the other providers from being tried. - } - - if (artwork is null) - continue; - - // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract. - if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess) - continue; - - return new ResolvedArtwork(artwork, provider.Name); - } - return null; - } - - /// - /// Creates a cover artwork entity for the book identified by . - /// - /// The Id of the book the artwork belongs to. - /// The status of the artwork enrichment. - /// The relative file name of the stored artwork, if the artwork has been resolved. - /// The content hash of the stored artwork. - /// The name of the plugin that resolved the artwork, if applicable. - /// The date and time when the artwork was resolved, if applicable. - /// The created cover artwork entity. - private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc) - { - return new BookArtworkEntity - { - Id = Guid.NewGuid(), - BookId = bookId, - ArtworkType = ArtworkType.Cover, - Ordinal = 0, - FileName = fileName, - ContentHash = contentHash, - Status = status, - Provider = provider, - LastUpdateUtc = lastUpdateUtc, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - }; - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork"); - if (scanJobProgressResult.IsFailure) - return scanJobProgressResult.Errors; - - await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - return Result.Success; - } - - /// - /// The artwork resolved for a book, along with the provider that supplied it. - /// - /// The resolved artwork of the book. - /// The name of the provider that supplied the artwork. - private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index 7db6d886..86b77f91 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -1,33 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata; -using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using System; -using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -37,13 +18,11 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// /// Media library scan job for enriching the metadata of the media library items, using the metadata providers configured for the media library. -/// The enriched metadata is applied to the books, and the media contributors discovered while enriching the metadata are linked to them. +/// The enrichment itself is delegated to the metadata enricher of the media library type. /// internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanMetadataEnrichmentJob { - private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly ILogger _logger; /// /// Initializes a new instance of the class. @@ -52,11 +31,9 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo /// Injected factory for creating scopes in which services are requested. /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. /// - /// Injected logger used to report the issues encountered while enriching the metadata. - public MediaLibraryScanMetadataEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger logger) + public MediaLibraryScanMetadataEnrichmentJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; - _logger = logger; } /// @@ -87,110 +64,22 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // Load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment. - bool canDownloadMetadataFromWeb = false; - if (unitOfWork.LibraryRepository is not null) - { - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - _logger.LogWarning("Failed to read the media library, the providers requiring the web will not be used."); - else - canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; - } + // Load the media library, whose type determines the metadata enricher to use. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryType libraryType = getLibraryResult.Value.LibraryType; - // Get the metadata providers configured for the media library, in their configured order, that support the media library type, - // skipping the providers that require access to the web when the media library does not permit downloading data from the web. - Result> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - throw new InvalidOperationException(getConfigurationsResult.FirstError.Description); - List providers = []; - foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) - { - List configuredProviders = [.. asyncServiceScope.ServiceProvider - .GetKeyedServices(configuration.PluginId) - .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) - && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; - if (configuredProviders.Count == 0) - _logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); - providers.AddRange(configuredProviders); - } + IMediaLibraryScanMetadataEnricher? metadataEnricher = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); + if (metadataEnricher is null) + throw new InvalidOperationException($"No metadata enricher exists for media library type '{libraryType}'."); - // Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing. - bool shouldAggregateMetadataWhenMissing = false; - if (unitOfWork.UserSettingsRepository is not null) - { - Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false); - if (getUserSettingsResult.IsFailure) - _logger.LogWarning("Failed to read the user settings, the metadata will not be aggregated across providers."); - else - shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; - } + await metadataEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false); - // When no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely. - if (providers.Count > 0) - { - Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getBooksToEnrichCountResult.IsFailure) - throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); - int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - - // Set the initial progress of the scan job. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - int processedBooksCount = 0; - - // The contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only - // created once even when the same person is discovered for many books of the same page. - Dictionary contributorsByNormalizedName = []; - - // Process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size. - string? lastPath = null; - while (true) - { - cancellationToken.ThrowIfCancellationRequested(); - - Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); - if (getBooksPageResult.IsFailure) - throw new InvalidOperationException(getBooksPageResult.FirstError.Description); - IReadOnlyList booksPage = getBooksPageResult.Value; - if (booksPage.Count == 0) - break; - - foreach (BookEntity bookEntity in booksPage) - { - cancellationToken.ThrowIfCancellationRequested(); - - await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.BookRepository, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); - - // Check if enough time has passed since the last update. - DateTime now = DateTime.UtcNow; - if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) - { - // Increment the number of processed elements progress. - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - lastUpdateTime = now; - } - } - - // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. - Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - throw new InvalidOperationException(saveChangesResult.FirstError.Description); - unitOfWork.ClearTrackedEntities(); - contributorsByNormalizedName.Clear(); - - lastPath = booksPage[^1].Path; - } - } - else - _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value); - + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) @@ -213,237 +102,4 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); } } - - /// - /// Enriches the metadata of the provided , using the provided metadata providers in their configured order, - /// linking the media contributors discovered while enriching to the book. - /// - /// The book whose metadata is enriched. - /// The metadata providers, in their configured order. - /// Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not. - /// The repository used to persist the enriched book. - /// The repository used to persist the media contributors discovered while enriching. - /// The cache of the media contributors discovered in the current page, keyed by their normalized display name. - /// Cancellation token that can be used to stop the execution. - private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, CancellationToken cancellationToken) - { - // Convert the book to a domain object. - Result getBookResult = bookEntity.ToDomainEntity(); - if (getBookResult.IsFailure) - return; - Book book = getBookResult.Value; - - BookMetadataLookupDto bookMetadataLookup = new( - LibraryId: bookEntity.LibraryId, - Path: bookEntity.Path, - Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: This should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results. - OpenLibraryId: bookEntity.OpenLibraryId, - Title: bookEntity.Title, - Author: null, - LanguageCode: bookEntity.LanguageCode - ); - - ResolvedMetadata? resolvedMetadata = shouldAggregateMetadataWhenMissing - ? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false) - : await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false); - - if (resolvedMetadata is null) - { - // No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata. - bookEntity.MetadataStatus = MetadataStatus.Failed; - bookEntity.UpdatedOnUtc = DateTime.UtcNow; - bookEntity.UpdatedBy = Guid.NewGuid(); - return; - } - - // Apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns. - book.ApplyMetadata(resolvedMetadata.Metadata); - bookEntity.ApplyMetadataToEntity(book); - - // Link the media contributors discovered while enriching to the book, finding or creating a single contributor per person. - List linkedContributors = []; - List domainContributors = []; - foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? []) - { - if (contributor.Name?.DisplayName is null) - continue; - - MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false); - - MediaContributorRole role = contributor.Role ?? MediaContributorRole.Author; - if (linkedContributors.Any(linkedContributor => linkedContributor.MediaContributorId == contributorEntity.Id && linkedContributor.Role == role)) - continue; - linkedContributors.Add(new BookContributorEntity - { - Id = Guid.NewGuid(), - BookId = bookEntity.Id, - MediaContributorId = contributorEntity.Id, - Role = role, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - }); - domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value); - } - bookEntity.Contributors.Clear(); - bookEntity.Contributors.AddRange(linkedContributors); - book.UpdateContributors(domainContributors); - - // Mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern. - bookEntity.MetadataStatus = MetadataStatus.Enriched; - bookEntity.MetadataProvider = resolvedMetadata.ProviderName; - bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow; - } - - /// - /// Finds the media contributor with the name of the provided , or creates it, caching it by its normalized display name - /// so that a contributor is only created once even when the same person is discovered for many books of the same page. - /// - /// The repository used to persist the media contributors discovered while enriching. - /// The cache of the media contributors discovered in the current page, keyed by their normalized display name. - /// The contributor to find or create. - /// Cancellation token that can be used to stop the execution. - /// The found or created media contributor. - private async Task FindOrCreateContributorAsync(IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, MediaContributorDto contributor, CancellationToken cancellationToken) - { - string displayName = contributor.Name!.DisplayName!; - string normalizedDisplayName = displayName.ToLowerInvariant(); - - if (contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? cachedContributor)) - return cachedContributor; - - Result getContributorResult = await mediaContributorRepository.FindOrCreateByDisplayNameAsync(displayName, null, cancellationToken).ConfigureAwait(false); - if (getContributorResult.IsFailure) - throw new InvalidOperationException(getContributorResult.FirstError.Description); - - contributorsByNormalizedName[normalizedDisplayName] = getContributorResult.Value; - return getContributorResult.Value; - } - - /// - /// Tries the in order, applying the metadata of the first one that returns usable metadata. - /// - /// The book onto which the metadata is applied. - /// The lookup describing the book. - /// The metadata providers, in their configured order. - /// Cancellation token that can be used to stop the execution. - /// The applied metadata and the provider that supplied it, or when no provider returned usable metadata. - private static async Task TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) - { - foreach (IMetadataProvider metadataProvider in metadataProviders) - { - try - { - MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); - if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata)) - continue; - - Result applyMetadataResult = book.ApplyMetadata(bookMetadata); - if (applyMetadataResult.IsFailure) - continue; - return new ResolvedMetadata(bookMetadata, metadataProvider.Name); - } - catch (Exception) - { - // A failing metadata provider must not prevent the other providers from being tried. - } - } - return null; - } - - /// - /// Aggregates the metadata of the from all the , in their configured order, filling the fields that the earlier providers lack with the values of the later ones. - /// - /// The book onto which the aggregated metadata is applied. - /// The lookup describing the book. - /// The metadata providers, in their configured order. - /// Cancellation token that can be used to stop the execution. - /// The applied aggregated metadata and the providers that contributed to it, or when no provider returned usable metadata. - private static async Task AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) - { - BookMetadataDto? mergedMetadata = null; - List contributingProviders = []; - - foreach (IMetadataProvider metadataProvider in metadataProviders) - { - try - { - MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); - if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata)) - continue; - - mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata); - contributingProviders.Add(metadataProvider.Name); - // The identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely. - bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata); - } - catch (Exception) - { - // A failing metadata provider must not prevent the other providers from being tried. - } - } - - if (mergedMetadata is null) - return null; - - Result applyMetadataResult = book.ApplyMetadata(mergedMetadata); - return applyMetadataResult.IsFailure ? null : new ResolvedMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal))); - } - - /// - /// Enriches the with the identifiers and the title discovered by the already queried metadata providers. - /// - /// The lookup to enrich. - /// The metadata discovered by the already queried metadata providers. - /// The enriched lookup. - private static BookMetadataLookupDto EnrichLookup(BookMetadataLookupDto bookMetadataLookup, BookMetadataDto bookMetadata) - { - string? isbn = bookMetadataLookup.Isbn ?? bookMetadata.Isbns?.FirstOrDefault()?.Value; - string? openLibraryId = bookMetadataLookup.OpenLibraryId ?? bookMetadata.OpenLibraryId; - string? title = bookMetadataLookup.Title ?? bookMetadata.Title; - return bookMetadataLookup with - { - Isbn = isbn, - OpenLibraryId = openLibraryId, - Title = title - }; - } - - /// - /// Determines whether the provided is usable, meaning it has a title. - /// - /// The metadata to validate. - /// when the metadata is usable, otherwise . - private static bool IsUsableMetadata(BookMetadataDto bookMetadata) - { - return !string.IsNullOrWhiteSpace(bookMetadata.Title); - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata"); - if (scanJobProgressResult.IsFailure) - return scanJobProgressResult.Errors; - - await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - return Result.Success; - } - - /// - /// The metadata resolved for a book, along with the providers that supplied it. - /// - /// The resolved metadata of the book. - /// The name of the provider, or the providers, that supplied the metadata. - private sealed record ResolvedMetadata(BookMetadataDto Metadata, string ProviderName); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs index 40b350c9..73d9af1c 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs @@ -13,6 +13,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -82,6 +83,13 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); LibraryEntity library = getLibraryResult.Value; + // The type of the media library determines the materializer whose enrichment state is invalidated. + IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == library.LibraryType); + if (materializer is null) + throw new InvalidOperationException($"No media library item materializer exists for media library type '{library.LibraryType}'."); + // Load the provider configurations of the media library, whose fingerprint is compared against the stored one. Result> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getMetadataConfigurationsResult.IsFailure) @@ -91,33 +99,46 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med if (getArtworkConfigurationsResult.IsFailure) throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description); - // Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing. + // Read whether the metadata and the artwork of the items of the user are aggregated from multiple providers, when missing. bool shouldAggregateMetadataWhenMissing = false; + bool shouldAggregateArtworkWhenMissing = false; if (unitOfWork.UserSettingsRepository is not null) { Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false); if (getUserSettingsResult.IsFailure) - _logger.LogWarning("Failed to read the user settings, the metadata provider configuration fingerprint will not include the metadata aggregation setting."); + _logger.LogWarning("Failed to read the user settings, the provider configuration fingerprints will not include the aggregation settings."); else + { shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; + shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false; + } } // Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration // changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration // was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored. string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb); - string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, library.CanDownloadMetadataFromWeb); + string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, shouldAggregateArtworkWhenMissing, library.CanDownloadMetadataFromWeb); + string pathTemplateFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([.. library.PathTemplateParts]); if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint) { - Result resetMetadataResult = await unitOfWork.BookRepository.ResetMetadataStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result resetMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); if (resetMetadataResult.IsFailure) throw new InvalidOperationException(resetMetadataResult.FirstError.Description); } + // A path template change invalidates the metadata derived from the paths, so the metadata state is reset as well. + if (library.PathTemplateFingerprint is not null && library.PathTemplateFingerprint != pathTemplateFingerprint) + { + Result resetPathTemplateMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (resetPathTemplateMetadataResult.IsFailure) + throw new InvalidOperationException(resetPathTemplateMetadataResult.FirstError.Description); + } + if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint) { - Result resetArtworkResult = await unitOfWork.BookRepository.ResetArtworkStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result resetArtworkResult = await materializer.ResetArtworkStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false); if (resetArtworkResult.IsFailure) throw new InvalidOperationException(resetArtworkResult.FirstError.Description); } @@ -127,6 +148,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med // update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed. library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; + library.PathTemplateFingerprint = pathTemplateFingerprint; library.UpdatedOnUtc = DateTime.UtcNow; library.UpdatedBy = Guid.NewGuid(); @@ -139,6 +161,8 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index b78a12d1..86556917 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -1,10 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; @@ -13,9 +11,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; #endregion @@ -67,9 +63,20 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + // Load the media library, whose type determines the materializer used to create the media library items. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryType libraryType = getLibraryResult.Value.LibraryType; + + IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); + if (materializer is null) + throw new InvalidOperationException($"No media library item materializer exists for media library type '{libraryType}'."); + // Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium. Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) @@ -80,7 +87,7 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed if (getDeletedPathsResult.IsFailure) throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description); - // Get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched. + // Get the paths of the media library scan staging results that changed since the previous scan, so that the items stored at those paths are re-enriched. Result> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); if (getChangedPathsResult.IsFailure) throw new InvalidOperationException(getChangedPathsResult.FirstError.Description); @@ -90,10 +97,10 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed if (applySnapshotSwapResult.IsFailure) throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description); - // Reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow. + // Reset the enrichment state of the media library items whose content changed, so that they are re-enriched by the enrichment jobs that follow. if (getChangedPathsResult.Value.Count > 0) { - Result resetEnrichmentStateResult = await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false); + Result resetEnrichmentStateResult = await materializer.ResetEnrichmentStateForChangedPathsAsync(unitOfWork, LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false); if (resetEnrichmentStateResult.IsFailure) throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description); } @@ -105,25 +112,15 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); } - // Materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata. + // Materialize the media library items from the scan snapshot, so that they are browsable even without web metadata. Result> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getPathsResult.IsFailure) throw new InvalidOperationException(getPathsResult.FirstError.Description); - foreach (string path in getPathsResult.Value) - { - cancellationToken.ThrowIfCancellationRequested(); + Result materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false); + if (materializeItemsResult.IsFailure) + throw new InvalidOperationException(materializeItemsResult.FirstError.Description); - Result getExistingBookResult = await unitOfWork.BookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false); - if (getExistingBookResult.IsFailure) - throw new InvalidOperationException(getExistingBookResult.FirstError.Description); - if (getExistingBookResult.Value is not null) - continue; - - Result insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false); - if (insertBookResult.IsFailure) - throw new InvalidOperationException(insertBookResult.FirstError.Description); - } Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) throw new InvalidOperationException(saveChangesResult.FirstError.Description); @@ -133,6 +130,8 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) @@ -175,38 +174,4 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed return Result.Success; } - - /// - /// Creates a shell book entity for the file stored at in the media library identified by , - /// with a title derived from the file name, and no web metadata yet. - /// - /// The Id of the media library the book belongs to. - /// The file system path of the book. - /// The created shell book entity. - private static BookEntity CreateShellBookEntity(Guid libraryId, string path) - { - return new BookEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - Path = path, - Title = GetTitleFromPath(path), - MetadataStatus = MetadataStatus.Pending, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - }; - } - - /// - /// Derives a book title from the file name of the provided , by removing the extension and replacing separators with spaces. - /// - /// The file system path of the book. - /// The derived title. - private static string GetTitleFromPath(string path) - { - string fileName = Path.GetFileNameWithoutExtension(path); - string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim(); - return title.Length > 0 ? title : fileName; - } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs index 3c3c9208..03387db0 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.Plugins; using System; using System.Collections.Generic; @@ -38,14 +39,30 @@ internal static class ProviderConfigurationFingerprint /// Computes the fingerprint of the artwork provider configuration of a media library. /// /// The artwork provider configurations of the media library. + /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Whether the media library permits downloading data from the web. /// The fingerprint of the artwork provider configuration. - public static string ComputeArtworkFingerprint(IReadOnlyList configurations, bool canDownloadMetadataFromWeb) + public static string ComputeArtworkFingerprint(IReadOnlyList configurations, bool shouldAggregateArtworkWhenMissing, bool canDownloadMetadataFromWeb) { StringBuilder canonicalRepresentation = new(); foreach (LibraryArtworkProviderConfigurationEntity configuration in configurations.OrderBy(configuration => configuration.Rank)) canonicalRepresentation.Append($"{configuration.PluginId:D}|{configuration.IsEnabled}|{configuration.Rank};"); - canonicalRepresentation.Append($"web:{canDownloadMetadataFromWeb};"); + canonicalRepresentation.Append($"aggregate:{shouldAggregateArtworkWhenMissing};web:{canDownloadMetadataFromWeb};"); + + return ComputeFingerprint(canonicalRepresentation.ToString()); + } + + /// + /// Computes the fingerprint of the path template of a media library, used to detect whether the template changed + /// since the last scan, and thus whether the metadata of the library items needs to be derived from their paths again. + /// + /// The ordered parts of the path template of the media library. + /// The fingerprint of the path template. + public static string ComputePathTemplateFingerprint(IReadOnlyList parts) + { + StringBuilder canonicalRepresentation = new(); + foreach (LibraryPathTemplatePartEntity part in parts.OrderBy(part => part.Position)) + canonicalRepresentation.Append($"{part.Kind}|{part.Representation}|{part.IsOptional};"); return ComputeFingerprint(canonicalRepresentation.ToString()); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs new file mode 100644 index 00000000..51953e6a --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs @@ -0,0 +1,378 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Artwork enricher for the media library items of the books media library type, using the artwork providers configured for the media library. +/// +/// +/// The artwork is tracked per book, per type and ordinal, so that a change of one artwork does not require the others to be re-fetched. +/// +internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanArtworkEnricher +{ + private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// The media library type that this artwork enricher supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating scopes in which services are requested. + /// Injected logger used to report the issues encountered while resolving the artwork. + public BooksMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Resolves the artwork of the books of the provided media library, using the artwork providers configured for it. + /// + /// The unique identifier of the media library whose artwork is resolved. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken) + { + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId); + + // Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines + // whether the providers that require access to the web are used during the enrichment. + string libraryName = string.Empty; + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used."); + else + { + libraryName = getLibraryResult.Value.Title; + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + } + + // Get the artwork providers configured for the media library, in their configured order, that support the media library type. + // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding. + List artworkProviders = []; + if (unitOfWork.ArtworkProviderConfigurationRepository is not null) + { + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + _logger.LogWarning("Failed to read the artwork provider configurations."); + else + { + foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); + artworkProviders.AddRange(configuredProviders); + } + } + } + + // When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely. + if (artworkProviders.Count > 0) + { + IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + + Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getBooksToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); + int totalBooksToEnrich = getBooksToEnrichCountResult.Value; + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedBooksCount = 0; + + // Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size. + string? lastPath = null; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(libraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getBooksPageResult.IsFailure) + throw new InvalidOperationException(getBooksPageResult.FirstError.Description); + IReadOnlyList booksPage = getBooksPageResult.Value; + if (booksPage.Count == 0) + break; + + // Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory. + Result> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false); + if (getAuthorsResult.IsFailure) + throw new InvalidOperationException(getAuthorsResult.FirstError.Description); + + foreach (BookEntity bookEntity in booksPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false); + + // Check if enough time has passed since the last update. + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // Increment the number of processed elements progress. + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); + unitOfWork.ClearTrackedEntities(); + + lastPath = booksPage[^1].Path; + } + } + else + _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value); + } + + /// + /// Resolves the cover artwork of the provided from the , in their configured order, + /// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book. + /// + /// The book whose artwork is resolved. + /// The artwork providers, in their configured order. + /// The service used to store the artwork of the book. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the book belongs to. + /// The display names of the authors of the books of the current page, keyed by the Id of the book. + /// Cancellation token that can be used to stop the execution. + private static async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary authorsDisplayNamesByBookId, CancellationToken cancellationToken) + { + // When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped. + if (bookArtworkService is null || artworkProviders.Count == 0) + return; + + ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false); + // The books media library type tracks a single cover, so only the cover returned by the provider is stored. + ArtworkDto? resolvedCover = resolvedArtwork?.Artworks.FirstOrDefault(artwork => artwork.Type == ArtworkType.Cover); + if (resolvedCover is null || resolvedArtwork is null) + { + // No artwork provider returned a usable cover, so the cover artwork of the book is marked as failed to resolve. + BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + if (coverArtwork is null) + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); + else + { + coverArtwork.Status = ArtworkStatus.Failed; + coverArtwork.UpdatedOnUtc = DateTime.UtcNow; + coverArtwork.UpdatedBy = Guid.NewGuid(); + } + return; + } + + BookArtworkEntity? existingCoverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + + // When the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one + // is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it. + ulong contentHash = 0; + bool shouldStoreArtwork = true; + if (!string.IsNullOrWhiteSpace(resolvedCover.LocalPath)) + { + contentHash = fileHashService.ComputeFileHash(resolvedCover.LocalPath); + shouldStoreArtwork = existingCoverArtwork is null || contentHash != existingCoverArtwork.ContentHash; + } + + if (shouldStoreArtwork) + { + string authorName = authorsDisplayNamesByBookId.TryGetValue(bookEntity.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; + Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedCover, cancellationToken).ConfigureAwait(false); + if (saveArtworkResult.IsFailure) + { + // A failing artwork storage must not prevent the book from being tracked as failed to resolve. + if (existingCoverArtwork is null) + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); + else + { + existingCoverArtwork.Status = ArtworkStatus.Failed; + existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedBy = Guid.NewGuid(); + } + return; + } + + // For remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one. + if (contentHash == 0) + { + string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\')); + contentHash = fileHashService.ComputeFileHash(storedArtworkPath); + } + + if (existingCoverArtwork is null) + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); + else + { + existingCoverArtwork.FileName = saveArtworkResult.Value; + existingCoverArtwork.ContentHash = contentHash; + existingCoverArtwork.Status = ArtworkStatus.Enriched; + existingCoverArtwork.Provider = resolvedArtwork.ProviderName; + existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedBy = Guid.NewGuid(); + } + } + else + { + // The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched. + existingCoverArtwork!.Status = ArtworkStatus.Enriched; + existingCoverArtwork.Provider = resolvedArtwork.ProviderName; + existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedBy = Guid.NewGuid(); + } + } + + /// + /// Resolves the artwork of the from the , in their configured order, + /// returning the artwork of the first provider that returns it. + /// + /// The book whose artwork is resolved. + /// The artwork providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork and the provider that supplied it, or when no provider returned usable artwork. + private static async Task ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, CancellationToken cancellationToken) + { + BookMetadataLookupDto artworkLookup = new( + LibraryId: bookEntity.LibraryId, + Path: bookEntity.Path, + Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, + OpenLibraryId: bookEntity.OpenLibraryId, + Title: bookEntity.Title, + Author: null, + LanguageCode: bookEntity.LanguageCode + ); + + foreach (IArtworkProvider provider in artworkProviders) + { + IReadOnlyList artworks = []; + try + { + artworks = await provider.GetArtworkAsync(artworkLookup, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + // A failing artwork provider must not prevent the other providers from being tried. + } + + // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract. + IReadOnlyList usableArtworks = [.. artworks.Where(artwork => artwork.Type == ArtworkType.Cover && (string.IsNullOrWhiteSpace(artwork.RemoteUrl) || provider.RequiresWebAccess))]; + if (usableArtworks.Count == 0) + continue; + + return new ResolvedArtwork(usableArtworks, provider.Name); + } + return null; + } + + /// + /// Creates a cover artwork entity for the book identified by . + /// + /// The Id of the book the artwork belongs to. + /// The status of the artwork enrichment. + /// The relative file name of the stored artwork, if the artwork has been resolved. + /// The content hash of the stored artwork. + /// The name of the plugin that resolved the artwork, if applicable. + /// The date and time when the artwork was resolved, if applicable. + /// The created cover artwork entity. + private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc) + { + return new BookArtworkEntity + { + Id = Guid.NewGuid(), + BookId = bookId, + ArtworkType = ArtworkType.Cover, + Ordinal = 0, + FileName = fileName, + ContentHash = contentHash, + Status = status, + Provider = provider, + LastUpdateUtc = lastUpdateUtc, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The unique identifier of the media library being scanned. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private static async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } + + /// + /// The artwork resolved for a book, along with the provider that supplied it. + /// + /// The resolved artworks of the book. + /// The name of the provider that supplied the artwork. + private sealed record ResolvedArtwork(IReadOnlyList Artworks, string ProviderName); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs new file mode 100644 index 00000000..10993745 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs @@ -0,0 +1,205 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Materializer for the media library items of the books media library type. +/// +internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanItemMaterializer +{ + private readonly ILibraryPathTemplateService _pathTemplateService; + private readonly IPathService _pathService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for deriving the metadata of the books from their paths. + /// Injected service for handling file system paths. + public BooksMediaLibraryScanItemMaterializer(ILibraryPathTemplateService pathTemplateService, IPathService pathService) + { + _pathTemplateService = pathTemplateService; + _pathService = pathService; + } + + /// + /// The media library type that this materializer supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Resets the enrichment state of the books stored at the provided . + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose books are reset. + /// The file system paths of the books whose enrichment state is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetEnrichmentStateForChangedPathsAsync(IUnitOfWork unitOfWork, Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken) + { + return await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(libraryId, paths, cancellationToken).ConfigureAwait(false); + } + + /// + /// Materializes the books of the media library from the paths of the media library scan snapshot. + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose books are materialized. + /// The Id of the media library scan whose results are materialized. + /// The file system paths of the media library scan snapshot. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList paths, CancellationToken cancellationToken) + { + // The library holds the path template that describes the structure of the library on disk, used to derive the metadata of each book from its path. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) + return domainLibraryResult.Errors; + Library library = domainLibraryResult.Value; + Result pathTemplateResult = _pathTemplateService.ResolveTemplate(library.LibraryType, library.PathTemplate.Parts); + if (pathTemplateResult.IsFailure) + return pathTemplateResult.Errors; + LibraryPathTemplate pathTemplate = pathTemplateResult.Value; + + // Books that are already stored are never inserted again, so a re-scan of an unchanged file does not duplicate its book. The existing paths are + // loaded in a single query, instead of one existence check per path, so that the number of round trips does not scale with the size of the library. + List stagedPaths = [.. paths]; + Result> getExistingPathsResult = await unitOfWork.BookRepository.GetExistingPathsAsync(libraryId, stagedPaths, cancellationToken).ConfigureAwait(false); + if (getExistingPathsResult.IsFailure) + return getExistingPathsResult.Errors; + HashSet existingPaths = [.. getExistingPathsResult.Value]; + + foreach (string path in paths) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (existingPaths.Contains(path)) + continue; + + Result insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(library, path, pathTemplate), cancellationToken).ConfigureAwait(false); + if (insertBookResult.IsFailure) + return insertBookResult.Errors; + } + return Result.Success; + } + + /// + /// Resets the metadata enrichment status of all the books of the media library identified by . + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose books are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetMetadataStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken) + { + return await unitOfWork.BookRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resets the artwork enrichment status of all the books of the media library identified by . + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose books are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetArtworkStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken) + { + return await unitOfWork.BookRepository.ResetArtworkStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates a shell book entity for the file stored at in the media library identified by . + /// + /// The media library the book belongs to. + /// The file system path of the book. + /// The template describing the structure of the media library on disk. + /// The created shell book entity. + private BookEntity CreateShellBookEntity(Library library, string path, LibraryPathTemplate pathTemplate) + { + string title = GetTitleFromPath(path); + float? volumeNumber = null; + + string relativePath = GetRelativePath(path, library.ContentLocations, _pathService); + Result> parsedPathResult = _pathTemplateService.Parse(library.LibraryType, pathTemplate, relativePath, _pathService.PathSeparator); + if (parsedPathResult.IsSuccess && parsedPathResult.Value.HasValue) + { + ParsedLibraryPath parsedPath = parsedPathResult.Value.Value; + Optional parsedTitle = parsedPath.GetString(LibraryPathPartKind.Title); + if (parsedTitle.HasValue) + title = parsedTitle.Value; + Optional parsedSeriesNumber = parsedPath.GetInt(LibraryPathPartKind.SeriesNumber); + if (parsedSeriesNumber.HasValue) + volumeNumber = parsedSeriesNumber.Value; + } + + return new BookEntity + { + Id = Guid.NewGuid(), + LibraryId = library.Id.Value, + Path = path, + Title = title, + VolumeNumber = volumeNumber, + MetadataStatus = MetadataStatus.Pending, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Derives a book title from the file name of the provided . + /// + /// The file system path of the book. + /// The derived title. + private string GetTitleFromPath(string path) + { + string fileName = _pathService.GetFileNameWithoutExtension(path); + string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim(); + return title.Length > 0 ? title : fileName; + } + + /// + /// Gets the path of the book stored at , relative to the content location of the media library it belongs to. + /// + /// The absolute file system path of the book. + /// The content locations of the media library the book belongs to. + /// The service used to determine whether the file is inside a content location of the media library. + /// The path of the book, relative to its content location, or the file name when no content location contains it. + private static string GetRelativePath(string path, IReadOnlyCollection contentLocations, IPathService pathService) + { + foreach (FileSystemPathId contentLocation in contentLocations) + { + if (pathService.IsPathWithin(path, contentLocation.Path)) + { + string relativePath = path[contentLocation.Path.Length..].TrimStart('\\', '/'); + if (relativePath.Length > 0) + return relativePath; + } + } + return pathService.GetFileName(path); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs new file mode 100644 index 00000000..4f204d21 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs @@ -0,0 +1,409 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Metadata enricher for the media library items of the books media library type, using the metadata providers configured for the media library. +/// The enriched metadata is applied to the books, and the media contributors discovered while enriching the metadata are linked to them. +/// +internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanMetadataEnricher +{ + private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// The media library type that this metadata enricher supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating scopes in which services are requested. + /// Injected logger used to report the issues encountered while enriching the metadata. + public BooksMediaLibraryScanMetadataEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Enriches the metadata of the books of the provided media library, using the metadata providers configured for it. + /// + /// The unique identifier of the media library whose books are enriched. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken) + { + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId); + + // Load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment. + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the providers requiring the web will not be used."); + else + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + + // Get the metadata providers configured for the media library, in their configured order, that support the media library type, + // skipping the providers that require access to the web when the media library does not permit downloading data from the web. + Result> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + throw new InvalidOperationException(getConfigurationsResult.FirstError.Description); + List providers = []; + foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.LookupType == typeof(BookMetadataLookupDto) + && provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); + providers.AddRange(configuredProviders); + } + + // Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing. + bool shouldAggregateMetadataWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) + { + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the metadata will not be aggregated across providers."); + else + shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; + } + + // When no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely. + if (providers.Count > 0) + { + Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getBooksToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); + int totalBooksToEnrich = getBooksToEnrichCountResult.Value; + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedBooksCount = 0; + + // The contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only + // created once even when the same person is discovered for many books of the same page. + Dictionary contributorsByNormalizedName = []; + + // Process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size. + string? lastPath = null; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(libraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getBooksPageResult.IsFailure) + throw new InvalidOperationException(getBooksPageResult.FirstError.Description); + IReadOnlyList booksPage = getBooksPageResult.Value; + if (booksPage.Count == 0) + break; + + foreach (BookEntity bookEntity in booksPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); + + // Check if enough time has passed since the last update. + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // Increment the number of processed elements progress. + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); + unitOfWork.ClearTrackedEntities(); + contributorsByNormalizedName.Clear(); + + lastPath = booksPage[^1].Path; + } + } + else + _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value); + } + + /// + /// Enriches the metadata of the provided , using the provided metadata providers in their configured order, + /// linking the media contributors discovered while enriching to the book. + /// + /// The book whose metadata is enriched. + /// The metadata providers, in their configured order. + /// Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not. + /// The repository used to persist the media contributors discovered while enriching. + /// The cache of the media contributors discovered in the current page, keyed by their normalized display name. + /// Cancellation token that can be used to stop the execution. + private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, CancellationToken cancellationToken) + { + // Convert the book to a domain object. + Result getBookResult = bookEntity.ToDomainEntity(); + if (getBookResult.IsFailure) + return; + Book book = getBookResult.Value; + + BookMetadataLookupDto bookMetadataLookup = new( + LibraryId: bookEntity.LibraryId, + Path: bookEntity.Path, + Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: This should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results. + OpenLibraryId: bookEntity.OpenLibraryId, + Title: bookEntity.Title, + Author: null, + LanguageCode: bookEntity.LanguageCode + ); + + ResolvedMetadata? resolvedMetadata = shouldAggregateMetadataWhenMissing + ? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false) + : await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false); + + if (resolvedMetadata is null) + { + // No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata. + bookEntity.MetadataStatus = MetadataStatus.Failed; + bookEntity.UpdatedOnUtc = DateTime.UtcNow; + bookEntity.UpdatedBy = Guid.NewGuid(); + return; + } + + // Apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns. + book.ApplyMetadata(resolvedMetadata.Metadata); + bookEntity.ApplyMetadataToEntity(book); + + // Link the media contributors discovered while enriching to the book, finding or creating a single contributor per person. + List linkedContributors = []; + List domainContributors = []; + foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? []) + { + if (contributor.Name?.DisplayName is null) + continue; + + MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false); + + MediaContributorRole role = contributor.Role ?? MediaContributorRole.Author; + if (linkedContributors.Any(linkedContributor => linkedContributor.MediaContributorId == contributorEntity.Id && linkedContributor.Role == role)) + continue; + linkedContributors.Add(new BookContributorEntity + { + Id = Guid.NewGuid(), + BookId = bookEntity.Id, + MediaContributorId = contributorEntity.Id, + Role = role, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }); + domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value); + } + bookEntity.Contributors.Clear(); + bookEntity.Contributors.AddRange(linkedContributors); + book.UpdateContributors(domainContributors); + + // Mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern. + bookEntity.MetadataStatus = MetadataStatus.Enriched; + bookEntity.MetadataProvider = resolvedMetadata.ProviderName; + bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow; + } + + /// + /// Finds the media contributor with the name of the provided , or creates it, caching it by its normalized display name + /// so that a contributor is only created once even when the same person is discovered for many books of the same page. + /// + /// The repository used to persist the media contributors discovered while enriching. + /// The cache of the media contributors discovered in the current page, keyed by their normalized display name. + /// The contributor to find or create. + /// Cancellation token that can be used to stop the execution. + /// The found or created media contributor. + private static async Task FindOrCreateContributorAsync(IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, MediaContributorDto contributor, CancellationToken cancellationToken) + { + string displayName = contributor.Name!.DisplayName!; + string normalizedDisplayName = displayName.ToLowerInvariant(); + + if (contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? cachedContributor)) + return cachedContributor; + + Result getContributorResult = await mediaContributorRepository.FindOrCreateByDisplayNameAsync(displayName, null, cancellationToken).ConfigureAwait(false); + if (getContributorResult.IsFailure) + throw new InvalidOperationException(getContributorResult.FirstError.Description); + + contributorsByNormalizedName[normalizedDisplayName] = getContributorResult.Value; + return getContributorResult.Value; + } + + /// + /// Tries the in order, applying the metadata of the first one that returns usable metadata. + /// + /// The book onto which the metadata is applied. + /// The lookup describing the book. + /// The metadata providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The applied metadata and the provider that supplied it, or when no provider returned usable metadata. + private static async Task TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) + { + foreach (IMetadataProvider metadataProvider in metadataProviders) + { + try + { + MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); + if (metadataResult is not BookMetadataDto bookMetadata || string.IsNullOrWhiteSpace(bookMetadata.Title)) + continue; + + Result applyMetadataResult = book.ApplyMetadata(bookMetadata); + if (applyMetadataResult.IsFailure) + continue; + return new ResolvedMetadata(bookMetadata, metadataProvider.Name); + } + catch (Exception) + { + // A failing metadata provider must not prevent the other providers from being tried. + } + } + return null; + } + + /// + /// Aggregates the metadata of the from all the , in their configured order, filling the fields that the earlier providers lack with the values of the later ones. + /// + /// The book onto which the aggregated metadata is applied. + /// The lookup describing the book. + /// The metadata providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The applied aggregated metadata and the providers that contributed to it, or when no provider returned usable metadata. + private static async Task AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) + { + BookMetadataDto? mergedMetadata = null; + List contributingProviders = []; + + foreach (IMetadataProvider metadataProvider in metadataProviders) + { + try + { + MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); + if (metadataResult is not BookMetadataDto bookMetadata || string.IsNullOrWhiteSpace(bookMetadata.Title)) + continue; + + mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata); + contributingProviders.Add(metadataProvider.Name); + // The identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely. + bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata); + } + catch (Exception) + { + // A failing metadata provider must not prevent the other providers from being tried. + } + } + + if (mergedMetadata is null) + return null; + + Result applyMetadataResult = book.ApplyMetadata(mergedMetadata); + return applyMetadataResult.IsFailure ? null : new ResolvedMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal))); + } + + /// + /// Enriches the with the identifiers and the title discovered by the already queried metadata providers. + /// + /// The lookup to enrich. + /// The metadata discovered by the already queried metadata providers. + /// The enriched lookup. + private static BookMetadataLookupDto EnrichLookup(BookMetadataLookupDto bookMetadataLookup, BookMetadataDto bookMetadata) + { + string? isbn = bookMetadataLookup.Isbn ?? bookMetadata.Isbns?.FirstOrDefault()?.Value; + string? openLibraryId = bookMetadataLookup.OpenLibraryId ?? bookMetadata.OpenLibraryId; + string? title = bookMetadataLookup.Title ?? bookMetadata.Title; + return bookMetadataLookup with + { + Isbn = isbn, + OpenLibraryId = openLibraryId, + Title = title + }; + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The unique identifier of the media library being scanned. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private static async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } + + /// + /// The metadata resolved for a book, along with the providers that supplied it. + /// + /// The resolved metadata of the book. + /// The name of the provider, or the providers, that supplied the metadata. + private sealed record ResolvedMetadata(BookMetadataDto Metadata, string ProviderName); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs index 1355aaff..33a82ee5 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs @@ -8,6 +8,8 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Common.Utilities; +using Lumina.Infrastructure.Common.Networking; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; @@ -240,7 +242,7 @@ internal sealed class BookArtworkService : IBookArtworkService return copyFileResult.Errors; // Rename the copied file to the standard naming. - Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}"); + Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToFileExtension()}"); if (renameFileResult.IsFailure) return renameFileResult.Errors; @@ -266,7 +268,7 @@ internal sealed class BookArtworkService : IBookArtworkService return Errors.FileSystemManagement.FileNotFound; // Download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size. - using HttpClient httpClient = _httpClientFactory.CreateClient(); + using HttpClient httpClient = _httpClientFactory.CreateClient(NamedHttpClients.ARTWORK_DOWNLOAD); string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}"); bool downloaded = false; try diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs index 968685da..1b6cb328 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Scheduling; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; @@ -103,6 +105,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await SynchronizeBundledThemesIfNeededAsync(stoppingToken).ConfigureAwait(false); + await EnsureTechnicalDataCleanupScheduledJobAsync(stoppingToken).ConfigureAwait(false); await ResumeActiveCyclesAsync(stoppingToken).ConfigureAwait(false); try { @@ -148,6 +151,74 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS } } + /// + /// Ensures that the default "Technical data cleanup at startup" scheduled job exists, so that installations created before + /// the job was added to the default jobs also clean up the invalid technical data at every application startup. + /// + /// Cancellation token that can be used to stop the execution. + /// + /// The job is only created on installations that already have scheduled jobs. On a fresh installation, before the application + /// setup has run, no scheduled jobs exist yet, and the setup flow seeds this job together with the other default jobs. + /// + private async Task EnsureTechnicalDataCleanupScheduledJobAsync(CancellationToken cancellationToken) + { + try + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository + .GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + { + _logger.LogWarning("Failed to read the scheduled jobs to ensure the technical data cleanup job: {Error}", getScheduledJobsResult.FirstError.Description); + return; + } + + IReadOnlyList scheduledJobs = getScheduledJobsResult.Value.Data; + // A fresh installation has no scheduled jobs yet, and the setup flow seeds the default jobs, including this one; when the + // job already exists, regardless of its status, it is not created again, so a job that was stopped or removed by the user stays that way. + if (scheduledJobs.Count == 0 || scheduledJobs.Any(scheduledJob => scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup)) + return; + + // The job is owned by the same user as the other scheduled jobs, which is the administrator account. + Guid ownerUserId = scheduledJobs[0].OwnerUserId; + ScheduledJobEntity technicalDataCleanupJob = new() + { + Id = Guid.NewGuid(), + Name = "Technical data cleanup at startup", + TaskType = ScheduledTaskType.TechnicalDataCleanup, + ScheduleType = ScheduleType.OnceAtStartup, + Status = ScheduledJobStatus.Active, + OwnerUserId = ownerUserId, + LastStartedOnUtc = null, + LastCompletedOnUtc = null, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = ownerUserId, + UpdatedOnUtc = null, + UpdatedBy = null + }; + Result insertScheduledJobResult = await unitOfWork.ScheduledJobRepository.InsertAsync(technicalDataCleanupJob, cancellationToken).ConfigureAwait(false); + if (insertScheduledJobResult.IsFailure) + { + _logger.LogWarning("Failed to insert the technical data cleanup scheduled job: {Error}", insertScheduledJobResult.FirstError.Description); + return; + } + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + { + _logger.LogWarning("Failed to save the technical data cleanup scheduled job: {Error}", saveChangesResult.FirstError.Description); + return; + } + _logger.LogInformation("Created the default 'Technical data cleanup at startup' scheduled job."); + } + catch (OperationCanceledException) { } + catch (Exception exception) + { + // Ensuring the technical data cleanup job at startup is best effort, so a failure here must never stop the scheduler. + _logger.LogWarning(exception, "Failed to ensure the technical data cleanup scheduled job."); + } + } + /// /// Resumes the execution cycles of the scheduled jobs whose cycle was active when the application shut down. /// diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs index ce493bfb..d7933a5a 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs @@ -36,6 +36,7 @@ public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService(), ScheduledTaskType.RepairThemes => _serviceProvider.GetRequiredService(), ScheduledTaskType.CleanScheduledJobExecutionHistory => _serviceProvider.GetRequiredService(), + ScheduledTaskType.TechnicalDataCleanup => _serviceProvider.GetRequiredService(), _ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType)) }; } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs new file mode 100644 index 00000000..8a56b8c6 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Microsoft.Extensions.Logging; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that cleans the technical data that is no longer valid. +/// +public class TechnicalDataCleanupTaskExecutor : IScheduledTaskExecutor +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for logging. + /// Injected unit of work for interacting with the data access layer repositories. + public TechnicalDataCleanupTaskExecutor(ILogger logger, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _logger = logger; + } + + /// + /// Executes the cleanup of the technical data that is no longer valid. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken) + { + Result failInterruptedScansResult = await _unitOfWork.LibraryScanRepository.FailInterruptedScansAsync(cancellationToken).ConfigureAwait(false); + if (failInterruptedScansResult.IsFailure) + return failInterruptedScansResult.Errors; + + _logger.LogInformation("Cleaned the technical data on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index a6d6e8c9..1ffd9bd4 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -31,6 +31,7 @@ + diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 6671a6dd..dfeb872c 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -2,7 +2,8 @@ "MediaSettings": { "RootDirectory": "media", "LibrariesDirectory": "libraries", - "BooksDirectory": "books" + "BooksDirectory": "books", + "MusicDirectory": "music" }, "PluginsSettings": { "Directory": "plugins" diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs index 09b9250c..855fce9e 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs @@ -29,10 +29,10 @@ public interface IArtworkProvider bool RequiresWebAccess { get; } /// - /// Gets the artwork of the media item described by . + /// Gets the artworks of the media item described by . /// /// The lookup describing the media item to get the artwork for. /// Cancellation token that can be used to stop the execution. - /// The artwork of the media item, or when no artwork was found. - Task GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); + /// The artworks of the media item, or an empty collection when no artwork was found. + Task> GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); } diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs index ea296737..e1f3b94b 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -14,21 +15,21 @@ public interface IArtworkProvider : IArtworkProvider where TLookup : MetadataLookupDto { /// - /// Gets the artwork of the media item described by . + /// Gets the artworks of the media item described by . /// /// The lookup describing the media item to get the artwork for. /// Cancellation token that can be used to stop the execution. - /// The artwork of the media item, or when no artwork was found. - Task GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken); + /// The artworks of the media item, or an empty collection when no artwork was found. + Task> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken); /// - /// Gets the artwork of the media item described by . + /// Gets the artworks of the media item described by . /// /// The lookup describing the media item to get the artwork for. /// Cancellation token that can be used to stop the execution. - /// The artwork of the media item, or when no artwork was found or the lookup is of another runtime type. - async Task IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) + /// The artworks of the media item, or an empty collection when no artwork was found or the lookup is of another runtime type. + async Task> IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) { - return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null; + return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : []; } } diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs index aef276fc..824f1ce4 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -23,6 +24,11 @@ public interface IMetadataProvider /// IReadOnlyList SupportedLibraryTypes { get; } + /// + /// Gets the type of the metadata lookup this provider accepts, used to select the provider that matches a given lookup. + /// + Type LookupType { get; } + /// /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. /// diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs index 980a4d9e..7ea2f873 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -32,15 +33,20 @@ public interface IMetadataProvider : IMetadataProvider /// The metadata of the media item, or when no metadata was found. Task GetMetadataAsync(TLookup lookup, CancellationToken cancellationToken); + /// + /// Gets the type of the metadata lookup this provider accepts. + /// + Type IMetadataProvider.LookupType => typeof(TLookup); + /// /// Searches for the metadata of the media item described by . /// /// The lookup describing the media item to search for. /// Cancellation token that can be used to stop the execution. - /// The collection of metadata candidates found for the media item. + /// The collection of metadata candidates found for the media item, or an empty collection when the lookup is of another runtime type. async Task> IMetadataProvider.GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) { - return await GetSearchResultsAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false); + return lookup is TLookup typedLookup ? await GetSearchResultsAsync(typedLookup, cancellationToken).ConfigureAwait(false) : []; } /// @@ -48,9 +54,9 @@ public interface IMetadataProvider : IMetadataProvider /// /// The lookup describing the media item to get the metadata for. /// Cancellation token that can be used to stop the execution. - /// The metadata of the media item, or when no metadata was found. + /// The metadata of the media item, or when no metadata was found or the lookup is of another runtime type. async Task IMetadataProvider.GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) { - return await GetMetadataAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false); + return lookup is TLookup typedLookup ? await GetMetadataAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null; } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index 364276fa..2f6fd0de 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -28,6 +28,7 @@ public static partial class ApiRoutes public const string GET_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers"; public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "/libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers/reorder"; + public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "/libraries/path-template-parts/{libraryType}"; public const string GET_LIBRARY_BOOK_READERS = "/libraries/{libraryId}/book-readers"; public const string SET_LIBRARY_BOOK_READER_ENABLED = "/libraries/{libraryId}/book-readers/{pluginId}/enabled"; } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs index a039dd41..26fc8125 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; @@ -41,18 +41,15 @@ public class AddAlbumEndpointSummary : Summary r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the album. Optional."); RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the album. Optional."); RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album. Optional."); - RequestParam(r => r.Metadata!.ReleaseType, "The type of the release. Optional."); + RequestParam(r => r.Metadata!.ReleaseTypes, "The type of the release. Optional."); RequestParam(r => r.Metadata!.ReleaseStatus, "The status of the release. Optional."); RequestParam(r => r.Metadata!.TotalDiscs, "The number of discs of the release. Optional."); RequestParam(r => r.Metadata!.TotalTracks, "The number of tracks of the release. Optional."); @@ -310,7 +329,7 @@ public class AddAlbumEndpointSummary : Summary r.Metadata!.Genres, "The list of genres associated with the album. Required."); RequestParam(r => r.MediaFormat, "The physical or digital medium of the album. Optional."); RequestParam(r => r.Barcode, "The barcode of the album. Optional."); - RequestParam(r => r.CatalogNumber, "The catalog number of the album. Optional."); + RequestParam(r => r.CatalogNumbers, "The catalog numbers of the album. Optional."); RequestParam(r => r.MusicBrainzReleaseId, "The MusicBrainz identifier of the release. Optional."); RequestParam(r => r.MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group. Optional."); RequestParam(r => r.MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist. Optional."); @@ -324,13 +343,13 @@ public class AddAlbumEndpointSummary : Summary(r => r.Metadata!.Title, "The title of the album."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the album, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the album, if applicable."); - ResponseParam(r => r.Metadata!.ReleaseType, "The type of the release, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseTypes, "The type of the release, if applicable."); ResponseParam(r => r.Metadata!.ReleaseStatus, "The status of the release, if applicable."); ResponseParam(r => r.Metadata!.TotalDiscs, "The number of discs of the release, if applicable."); ResponseParam(r => r.Metadata!.TotalTracks, "The number of tracks of the release."); ResponseParam(r => r.MediaFormat, "The physical or digital medium of the album, if applicable."); ResponseParam(r => r.Barcode, "The barcode of the album, if applicable."); - ResponseParam(r => r.CatalogNumber, "The catalog number of the album, if applicable."); + ResponseParam(r => r.CatalogNumbers, "The catalog numbers of the album, if applicable."); ResponseParam(r => r.MusicBrainzReleaseId, "The MusicBrainz identifier of the release, if applicable."); ResponseParam(r => r.MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group, if applicable."); ResponseParam(r => r.MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist, if applicable."); @@ -363,11 +382,12 @@ public class AddAlbumEndpointSummary : Summary ResponseParam(r => r.Metadata!.Title, "The title of the album."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the album, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the album, if applicable."); - ResponseParam(r => r.Metadata!.ReleaseType, "The type of the release, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseTypes, "The type of the release, if applicable."); ResponseParam(r => r.Metadata!.ReleaseStatus, "The status of the release, if applicable."); ResponseParam(r => r.Metadata!.TotalDiscs, "The number of discs of the release, if applicable."); ResponseParam(r => r.Metadata!.TotalTracks, "The number of tracks of the release."); ResponseParam(r => r.MediaFormat, "The physical or digital medium of the album, if applicable."); ResponseParam(r => r.Barcode, "The barcode of the album, if applicable."); - ResponseParam(r => r.CatalogNumber, "The catalog number of the album, if applicable."); + ResponseParam(r => r.CatalogNumbers, "The catalog numbers of the album, if applicable."); ResponseParam(r => r.MusicBrainzReleaseId, "The MusicBrainz identifier of the release, if applicable."); ResponseParam(r => r.MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group, if applicable."); ResponseParam(r => r.MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist, if applicable."); @@ -70,15 +70,16 @@ public class GetAlbumEndpointSummary : Summary Id: Guid.NewGuid(), ArtistId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), - Metadata: new AlbumMetadataDto( + Metadata: new MusicAlbumMetadataDto( Title: "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.", + Disambiguation: "original release", ReleaseInfo: new ReleaseInfoDto( OriginalReleaseDate: new DateOnly(1975, 11, 21), OriginalReleaseYear: 1975, - ReReleaseDate: default, - ReReleaseYear: default, + ReReleaseDate: new DateOnly(2011, 11, 21), + ReReleaseYear: 2011, ReleaseCountry: ReleaseCountry.GB, ReleaseVersion: "Remastered" ), @@ -100,19 +101,21 @@ public class GetAlbumEndpointSummary : Summary new TagDto(Name: "classic"), new TagDto(Name: "vinyl") ], - ReleaseType: MusicReleaseType.Album, + Script: "Latn", + ReleaseTypes: [MusicReleaseType.Album], ReleaseStatus: MusicReleaseStatus.Official, TotalDiscs: 1, TotalTracks: 12 ), MediaFormat: MusicMediaFormat.CD, + Packaging: MusicReleasePackaging.JewelCase, Barcode: "0042282778329", - CatalogNumber: "EMC 4008", + CatalogNumbers: ["EMC 4008"], + Label: "EMI", + ASIN: "B000002UTK", MusicBrainzReleaseId: Guid.NewGuid(), MusicBrainzReleaseGroupId: Guid.NewGuid(), MusicBrainzReleaseArtistId: Guid.NewGuid(), - CreatedOnUtc: DateTime.UtcNow, - UpdatedOnUtc: DateTime.UtcNow, Contributors: [ new MediaContributorReferenceDto( ContributorId: Guid.NewGuid(), @@ -137,6 +140,8 @@ public class GetAlbumEndpointSummary : Summary VoteCount: 1234 ) ], + CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), + UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc), Tracks: [] ) ); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs index 269da0ab..e9c3f688 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs @@ -41,10 +41,10 @@ public class GetAlbumTracksEndpointSummary : Summary(r => r.Script, "The script used by the language of the track, if applicable."); ResponseParam(r => r.Key, "The musical key of the track, if applicable."); ResponseParam(r => r.Bpm, "The tempo of the track in beats per minute, if applicable."); - ResponseParam(r => r.Work, "The title of the work the track is a recording of, if applicable."); + ResponseParam(r => r.Work!.Title, "The title of the work the track is a recording of, if applicable."); ResponseParam(r => r.MusicBrainzRecordingId, "The MusicBrainz identifier of the recording, if applicable."); ResponseParam(r => r.MusicBrainzTrackId, "The MusicBrainz identifier of the track, if applicable."); - ResponseParam(r => r.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); + ResponseParam(r => r.Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the track was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the track was last updated, if applicable."); ResponseParam(r => r.Moods, "The list of moods of the track."); @@ -80,15 +80,16 @@ public class GetAlbumTracksEndpointSummary : Summary r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the album. Optional."); RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the album. Optional."); RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album. Optional."); - RequestParam(r => r.Metadata!.ReleaseType, "The type of the release. Optional."); + RequestParam(r => r.Metadata!.ReleaseTypes, "The type of the release. Optional."); RequestParam(r => r.Metadata!.ReleaseStatus, "The status of the release. Optional."); RequestParam(r => r.Metadata!.TotalDiscs, "The number of discs of the release. Optional."); RequestParam(r => r.Metadata!.TotalTracks, "The number of tracks of the release. Optional."); @@ -57,7 +57,7 @@ public class UpdateAlbumEndpointSummary : Summary r.Metadata!.Tags, "The list of tags that further describe or categorize the album. Required."); RequestParam(r => r.MediaFormat, "The physical or digital medium of the album. Optional."); RequestParam(r => r.Barcode, "The barcode of the album. Optional."); - RequestParam(r => r.CatalogNumber, "The catalog number of the album. Optional."); + RequestParam(r => r.CatalogNumbers, "The catalog numbers of the album. Optional."); RequestParam(r => r.MusicBrainzReleaseId, "The MusicBrainz identifier of the release. Optional."); RequestParam(r => r.MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group. Optional."); RequestParam(r => r.MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist. Optional."); @@ -65,22 +65,19 @@ public class UpdateAlbumEndpointSummary : Summary r.Ratings, "The list of ratings for this album. Required."); ExampleRequest = new UpdateAlbumRequest( - Metadata: new AlbumMetadataDto( + Metadata: new MusicAlbumMetadataDto( Title: "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.", + Disambiguation: "original release", ReleaseInfo: new ReleaseInfoDto( OriginalReleaseDate: new DateOnly(1975, 11, 21), OriginalReleaseYear: 1975, - ReReleaseDate: default, - ReReleaseYear: default, + ReReleaseDate: new DateOnly(2011, 11, 21), + ReReleaseYear: 2011, ReleaseCountry: ReleaseCountry.GB, ReleaseVersion: "Remastered" ), - ReleaseType: MusicReleaseType.Album, - ReleaseStatus: MusicReleaseStatus.Official, - TotalDiscs: 1, - TotalTracks: 12, Language: new LanguageInfoDto( LanguageCode: "en", LanguageName: "English", @@ -100,11 +97,19 @@ public class UpdateAlbumEndpointSummary : Summary(r => r.Metadata!.Title, "The title of the album."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the album, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the album, if applicable."); - ResponseParam(r => r.Metadata!.ReleaseType, "The type of the release, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseTypes, "The type of the release, if applicable."); ResponseParam(r => r.Metadata!.ReleaseStatus, "The status of the release, if applicable."); ResponseParam(r => r.Metadata!.TotalDiscs, "The number of discs of the release, if applicable."); ResponseParam(r => r.Metadata!.TotalTracks, "The number of tracks of the release."); ResponseParam(r => r.MediaFormat, "The physical or digital medium of the album, if applicable."); ResponseParam(r => r.Barcode, "The barcode of the album, if applicable."); - ResponseParam(r => r.CatalogNumber, "The catalog number of the album, if applicable."); + ResponseParam(r => r.CatalogNumbers, "The catalog numbers of the album, if applicable."); ResponseParam(r => r.MusicBrainzReleaseId, "The MusicBrainz identifier of the release, if applicable."); ResponseParam(r => r.MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group, if applicable."); ResponseParam(r => r.MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist, if applicable."); @@ -177,15 +182,16 @@ public class UpdateAlbumEndpointSummary : Summary r.Name, "The name of the artist. Required."); + RequestParam(r => r.Metadata!.Name, "The name of the artist. Required."); RequestParam(r => r.Website, "The website of the artist. Optional."); RequestParam(r => r.MusicBrainzArtistId, "The MusicBrainz identifier of the artist. Optional."); RequestParam(r => r.Contributors, "The list of media contributors that make up the artist. Required."); @@ -308,20 +346,20 @@ public class AddArtistEndpointSummary : Summary r.Albums![0].Metadata!.Language, "The language of the album. Optional."); RequestParam(r => r.Albums![0].Metadata!.Language!.LanguageCode, "The ISO code of the language (e.g., \"en\" for English). Required."); RequestParam(r => r.Albums![0].Metadata!.Language!.LanguageName, "The name of the language in English. Required."); - RequestParam(r => r.Albums![0].Metadata!.Language!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); + RequestParam(r => r.Albums![0].Metadata!.Language!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage, "The original language of the album, if it has been translated. Optional."); RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the language (e.g., \"en\" for English). Required."); RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage!.LanguageName, "The name of the language in English. Required."); - RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); + RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); RequestParam(r => r.Albums![0].Metadata!.Tags, "The list of tags that further describe or categorize the album. Required."); RequestParam(r => r.Albums![0].Metadata!.Genres, "The list of genres associated with the album. Required."); - RequestParam(r => r.Albums![0].Metadata!.ReleaseType, "The type of the release. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseTypes, "The type of the release. Optional."); RequestParam(r => r.Albums![0].Metadata!.ReleaseStatus, "The status of the release. Optional."); RequestParam(r => r.Albums![0].Metadata!.TotalDiscs, "The number of discs of the release. Optional."); RequestParam(r => r.Albums![0].Metadata!.TotalTracks, "The number of tracks of the release. Optional."); RequestParam(r => r.Albums![0].MediaFormat, "The physical or digital medium of the album. Optional."); RequestParam(r => r.Albums![0].Barcode, "The barcode of the album. Optional."); - RequestParam(r => r.Albums![0].CatalogNumber, "The catalog number of the album. Optional."); + RequestParam(r => r.Albums![0].CatalogNumbers, "The catalog numbers of the album. Optional."); RequestParam(r => r.Albums![0].MusicBrainzReleaseId, "The MusicBrainz identifier of the release. Optional."); RequestParam(r => r.Albums![0].MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group. Optional."); RequestParam(r => r.Albums![0].MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist. Optional."); @@ -343,11 +381,11 @@ public class AddArtistEndpointSummary : Summary r.Albums![0].Tracks![0].Metadata!.Language, "The language of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.LanguageCode, "The ISO code of the language (e.g., \"en\" for English). Required."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.LanguageName, "The name of the language in English. Required."); - RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage, "The original language of the track, if it has been translated. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the language (e.g., \"en\" for English). Required."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.LanguageName, "The name of the language in English. Required."); - RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Tags, "The list of tags that further describe or categorize the track. Required."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Genres, "The list of genres associated with the track. Required."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds. Required."); @@ -361,10 +399,10 @@ public class AddArtistEndpointSummary : Summary r.Albums![0].Tracks![0].Script, "The script used by the language of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Key, "The musical key of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Bpm, "The tempo of the track in beats per minute. Optional."); - RequestParam(r => r.Albums![0].Tracks![0].Work, "The title of the work the track is a recording of. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Work!.Title, "The title of the work the track is a recording of. Optional."); RequestParam(r => r.Albums![0].Tracks![0].MusicBrainzRecordingId, "The MusicBrainz identifier of the recording. Optional."); RequestParam(r => r.Albums![0].Tracks![0].MusicBrainzTrackId, "The MusicBrainz identifier of the track. Optional."); - RequestParam(r => r.Albums![0].Tracks![0].MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Moods, "The list of moods of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Isrcs, "The list of ISRC (International Standard Recording Code) of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Contributors, "The list of media contributors that performed on the track. Required."); @@ -372,7 +410,7 @@ public class AddArtistEndpointSummary : Summary(r => r.Id, "The Id of the artist."); ResponseParam(r => r.LibraryId, "The Id of the media library this artist belongs to."); - ResponseParam(r => r.Name, "The name of the artist."); + ResponseParam(r => r.Metadata!.Name, "The name of the artist."); ResponseParam(r => r.Website, "The website of the artist, if applicable."); ResponseParam(r => r.MusicBrainzArtistId, "The MusicBrainz identifier of the artist, if applicable."); ResponseParam(r => r.Contributors, "The list of references to the media contributors that make up the artist, each with the role they played."); @@ -401,13 +439,13 @@ public class AddArtistEndpointSummary : Summary(r => r.Albums![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album."); ResponseParam(r => r.Albums![0].Metadata!.Tags, "The list of tags of the album."); ResponseParam(r => r.Albums![0].Metadata!.Genres, "The list of genres of the album."); - ResponseParam(r => r.Albums![0].Metadata!.ReleaseType, "The type of the release of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseTypes, "The type of the release of the album."); ResponseParam(r => r.Albums![0].Metadata!.ReleaseStatus, "The status of the release of the album."); ResponseParam(r => r.Albums![0].Metadata!.TotalDiscs, "The number of discs of the release of the album."); ResponseParam(r => r.Albums![0].Metadata!.TotalTracks, "The number of tracks of the release of the album."); ResponseParam(r => r.Albums![0].MediaFormat, "The physical or digital medium of the album, if applicable."); ResponseParam(r => r.Albums![0].Barcode, "The barcode of the album, if applicable."); - ResponseParam(r => r.Albums![0].CatalogNumber, "The catalog number of the album, if applicable."); + ResponseParam(r => r.Albums![0].CatalogNumbers, "The catalog numbers of the album, if applicable."); ResponseParam(r => r.Albums![0].MusicBrainzReleaseId, "The MusicBrainz identifier of the release, if applicable."); ResponseParam(r => r.Albums![0].MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group, if applicable."); ResponseParam(r => r.Albums![0].MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist, if applicable."); @@ -452,10 +490,10 @@ public class AddArtistEndpointSummary : Summary(r => r.Albums![0].Tracks![0].Script, "The script used by the language of the track, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].Key, "The musical key of the track, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].Bpm, "The tempo of the track in beats per minute, if applicable."); - ResponseParam(r => r.Albums![0].Tracks![0].Work, "The title of the work the track is a recording of, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].Work!.Title, "The title of the work the track is a recording of, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].MusicBrainzRecordingId, "The MusicBrainz identifier of the recording, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].MusicBrainzTrackId, "The MusicBrainz identifier of the track, if applicable."); - ResponseParam(r => r.Albums![0].Tracks![0].MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].CreatedOnUtc, "The date and time when the track was created."); ResponseParam(r => r.Albums![0].Tracks![0].UpdatedOnUtc, "The date and time when the track was last updated, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].Moods, "The list of moods of the track."); @@ -469,14 +507,39 @@ public class AddArtistEndpointSummary : Summary ResponseParam(r => r.Id, "The Id of the artist."); ResponseParam(r => r.LibraryId, "The Id of the media library this artist belongs to."); - ResponseParam(r => r.Name, "The name of the artist."); + ResponseParam(r => r.Metadata!.Name, "The name of the artist."); ResponseParam(r => r.Website, "The website of the artist, if applicable."); ResponseParam(r => r.MusicBrainzArtistId, "The MusicBrainz identifier of the artist, if applicable."); ResponseParam(r => r.Contributors, "The list of references to the media contributors that make up the artist, each with the role they played."); @@ -37,17 +43,127 @@ public class GetArtistEndpointSummary : Summary example: new ArtistResponse( Id: Guid.NewGuid(), LibraryId: Guid.NewGuid(), - Name: "Queen", + Metadata: new MusicArtistMetadataDto( + Name: "Queen", + SortName: "Queen", + Disambiguation: "British rock band", + Type: MusicArtistType.Group, + Gender: MusicArtistGender.NotApplicable, + Country: "GB", + Area: new MusicAreaDto(MusicBrainzAreaId: Guid.NewGuid(), Name: "United Kingdom", SortName: "United Kingdom", Disambiguation: "sovereign state", Type: "Country", Iso3166Code: "GB"), + BeginArea: new MusicAreaDto(MusicBrainzAreaId: Guid.NewGuid(), Name: "United Kingdom", SortName: "United Kingdom", Disambiguation: "sovereign state", Type: "Country", Iso3166Code: "GB"), + EndArea: new MusicAreaDto(MusicBrainzAreaId: Guid.NewGuid(), Name: "United Kingdom", SortName: "United Kingdom", Disambiguation: "sovereign state", Type: "Country", Iso3166Code: "GB"), + LifeSpanBegin: new DateOnly(1970, 6, 27), + LifeSpanEnd: new DateOnly(1991, 11, 24), + IsEnded: false, + Aliases: [new MusicArtistAliasDto(Name: "The Queen", SortName: "Queen", Type: "Artist name", Locale: "en", IsPrimary: false, BeginDate: new DateOnly(1970, 6, 27), EndDate: new DateOnly(1991, 11, 24), IsEnded: true)], + Genres: [new GenreDto(Name: "Rock")], + Tags: [new TagDto(Name: "classic")] + ), Website: "https://www.queenonline.com", MusicBrainzArtistId: Guid.NewGuid(), + Ipis: ["00012345678"], + Isnis: ["0000000123456789"], Contributors: [ - new(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Vocals), - new(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Guitar) + new MediaContributorReferenceDto(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Vocals), + new MediaContributorReferenceDto(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Guitar) ], - Albums: [], - CreatedOnUtc: DateTime.UtcNow, - UpdatedOnUtc: DateTime.UtcNow + CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), + UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc), + Ratings: [new AudioRatingDto(Value: 4.5M, MaxValue: 5, Source: AudioRatingSource.MusicBrainz, VoteCount: 2345)], + Albums: + [ + new( + Id: Guid.NewGuid(), + ArtistId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Metadata: new( + Title: "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.", + Disambiguation: "original release", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + 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"), + Genres: [new(Name: "Rock"), new(Name: "Progressive Rock")], + Tags: [new(Name: "classic"), new(Name: "vinyl")], + Script: "Latn", + ReleaseTypes: [MusicReleaseType.Album], + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Packaging: MusicReleasePackaging.JewelCase, + Barcode: "0042282778329", + CatalogNumbers: ["EMC 4008"], + Label: "EMI", + ASIN: "B000002UTK", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + Contributors: [new MediaContributorReferenceDto(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Producer)], + Ratings: [new(Value: 4.5M, MaxValue: 5, Source: AudioRatingSource.MusicBrainz, VoteCount: 2345)], + CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), + UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc), + 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)], + Ratings: [new(Value: 4.5M, MaxValue: 5, Source: AudioRatingSource.MusicBrainz, VoteCount: 2345)], + 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) + ) + ] + ) + ] ) ); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs index 447e7594..a70cc6d0 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs @@ -35,13 +35,13 @@ public class GetArtistAlbumsEndpointSummary : Summary(r => r.Metadata!.Title, "The title of the album."); ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the album, if applicable."); ResponseParam(r => r.Metadata!.Description, "The description of the album, if applicable."); - ResponseParam(r => r.Metadata!.ReleaseType, "The type of the release, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseTypes, "The type of the release, if applicable."); ResponseParam(r => r.Metadata!.ReleaseStatus, "The status of the release, if applicable."); ResponseParam(r => r.Metadata!.TotalDiscs, "The number of discs of the release, if applicable."); ResponseParam(r => r.Metadata!.TotalTracks, "The number of tracks of the release."); ResponseParam(r => r.MediaFormat, "The physical or digital medium of the album, if applicable."); ResponseParam(r => r.Barcode, "The barcode of the album, if applicable."); - ResponseParam(r => r.CatalogNumber, "The catalog number of the album, if applicable."); + ResponseParam(r => r.CatalogNumbers, "The catalog numbers of the album, if applicable."); ResponseParam(r => r.MusicBrainzReleaseId, "The MusicBrainz identifier of the release, if applicable."); ResponseParam(r => r.MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group, if applicable."); ResponseParam(r => r.MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist, if applicable."); @@ -72,15 +72,16 @@ public class GetArtistAlbumsEndpointSummary : Summary(r => r.Id, "The Id of the artist."); ResponseParam(r => r.LibraryId, "The Id of the media library this artist belongs to."); - ResponseParam(r => r.Name, "The name of the artist."); + ResponseParam(r => r.Metadata!.Name, "The name of the artist."); ResponseParam(r => r.Website, "The website of the artist, if applicable."); ResponseParam(r => r.MusicBrainzArtistId, "The MusicBrainz identifier of the artist, if applicable."); ResponseParam(r => r.Contributors, "The list of references to the media contributors that make up the artist, each with the role they played."); @@ -52,24 +59,244 @@ public class GetArtistsEndpointSummary : Summary r.Name, "The name of the artist. Required."); + RequestParam(r => r.Metadata!.Name, "The name of the artist. Required."); RequestParam(r => r.Website, "The website of the artist. Optional."); RequestParam(r => r.MusicBrainzArtistId, "The MusicBrainz identifier of the artist. Optional."); RequestParam(r => r.Contributors, "The list of media contributors that make up the artist. Required."); @@ -52,20 +52,20 @@ public class UpdateArtistEndpointSummary : Summary r.Albums![0].Metadata!.Language, "The language of the album. Optional."); RequestParam(r => r.Albums![0].Metadata!.Language!.LanguageCode, "The ISO code of the language (e.g., \"en\" for English). Required."); RequestParam(r => r.Albums![0].Metadata!.Language!.LanguageName, "The name of the language in English. Required."); - RequestParam(r => r.Albums![0].Metadata!.Language!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); + RequestParam(r => r.Albums![0].Metadata!.Language!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage, "The original language of the album, if it has been translated. Optional."); RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the language (e.g., \"en\" for English). Required."); RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage!.LanguageName, "The name of the language in English. Required."); - RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); + RequestParam(r => r.Albums![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); RequestParam(r => r.Albums![0].Metadata!.Tags, "The list of tags that further describe or categorize the album. Required."); RequestParam(r => r.Albums![0].Metadata!.Genres, "The list of genres associated with the album. Required."); - RequestParam(r => r.Albums![0].Metadata!.ReleaseType, "The type of the release. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseTypes, "The type of the release. Optional."); RequestParam(r => r.Albums![0].Metadata!.ReleaseStatus, "The status of the release. Optional."); RequestParam(r => r.Albums![0].Metadata!.TotalDiscs, "The number of discs of the release. Optional."); RequestParam(r => r.Albums![0].Metadata!.TotalTracks, "The number of tracks of the release. Optional."); RequestParam(r => r.Albums![0].MediaFormat, "The physical or digital medium of the album. Optional."); RequestParam(r => r.Albums![0].Barcode, "The barcode of the album. Optional."); - RequestParam(r => r.Albums![0].CatalogNumber, "The catalog number of the album. Optional."); + RequestParam(r => r.Albums![0].CatalogNumbers, "The catalog numbers of the album. Optional."); RequestParam(r => r.Albums![0].MusicBrainzReleaseId, "The MusicBrainz identifier of the release. Optional."); RequestParam(r => r.Albums![0].MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group. Optional."); RequestParam(r => r.Albums![0].MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist. Optional."); @@ -88,11 +88,11 @@ public class UpdateArtistEndpointSummary : Summary r.Albums![0].Tracks![0].Metadata!.Language, "The language of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.LanguageCode, "The ISO code of the language (e.g., \"en\" for English). Required."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.LanguageName, "The name of the language in English. Required."); - RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage, "The original language of the track, if it has been translated. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the language (e.g., \"en\" for English). Required."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.LanguageName, "The name of the language in English. Required."); - RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the language (e.g., \"Español\" for Spanish). Optional."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Tags, "The list of tags that further describe or categorize the track. Required."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Genres, "The list of genres associated with the track. Required."); RequestParam(r => r.Albums![0].Tracks![0].Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds. Required."); @@ -106,19 +106,37 @@ public class UpdateArtistEndpointSummary : Summary r.Albums![0].Tracks![0].Script, "The script used by the language of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Key, "The musical key of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Bpm, "The tempo of the track in beats per minute. Optional."); - RequestParam(r => r.Albums![0].Tracks![0].Work, "The title of the work the track is a recording of. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Work!.Title, "The title of the work the track is a recording of. Optional."); RequestParam(r => r.Albums![0].Tracks![0].MusicBrainzRecordingId, "The MusicBrainz identifier of the recording. Optional."); RequestParam(r => r.Albums![0].Tracks![0].MusicBrainzTrackId, "The MusicBrainz identifier of the track. Optional."); - RequestParam(r => r.Albums![0].Tracks![0].MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Moods, "The list of moods of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Isrcs, "The list of ISRC (International Standard Recording Code) of the track. Optional."); RequestParam(r => r.Albums![0].Tracks![0].Contributors, "The list of media contributors that performed on the track. Required."); RequestParam(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for this track. Required."); ExampleRequest = new UpdateArtistRequest( - Name: "Queen", + Metadata: new MusicArtistMetadataDto( + Name: "Queen", + SortName: "Queen", + Disambiguation: "British rock band", + Type: MusicArtistType.Group, + Gender: MusicArtistGender.NotApplicable, + Country: "GB", + Area: new MusicAreaDto(MusicBrainzAreaId: Guid.NewGuid(), Name: "United Kingdom", SortName: "United Kingdom", Disambiguation: "sovereign state", Type: "Country", Iso3166Code: "GB"), + BeginArea: new MusicAreaDto(MusicBrainzAreaId: Guid.NewGuid(), Name: "United Kingdom", SortName: "United Kingdom", Disambiguation: "sovereign state", Type: "Country", Iso3166Code: "GB"), + EndArea: new MusicAreaDto(MusicBrainzAreaId: Guid.NewGuid(), Name: "United Kingdom", SortName: "United Kingdom", Disambiguation: "sovereign state", Type: "Country", Iso3166Code: "GB"), + LifeSpanBegin: new DateOnly(1970, 6, 27), + LifeSpanEnd: new DateOnly(1991, 11, 24), + IsEnded: false, + Aliases: [new MusicArtistAliasDto(Name: "The Queen", SortName: "Queen", Type: "Artist name", Locale: "en", IsPrimary: false, BeginDate: new DateOnly(1970, 6, 27), EndDate: new DateOnly(1991, 11, 24), IsEnded: true)], + Genres: [new GenreDto(Name: "Rock")], + Tags: [new TagDto(Name: "classic")] + ), Website: "https://www.queenonline.com", MusicBrainzArtistId: Guid.NewGuid(), + Ipis: ["00012345678"], + Isnis: ["0000000123456789"], Contributors: [ new MediaContributorReferenceDto( @@ -130,18 +148,20 @@ public class UpdateArtistEndpointSummary : Summary(r => r.Id, "The Id of the artist."); ResponseParam(r => r.LibraryId, "The Id of the media library this artist belongs to."); - ResponseParam(r => r.Name, "The name of the artist."); + ResponseParam(r => r.Metadata!.Name, "The name of the artist."); ResponseParam(r => r.Website, "The website of the artist, if applicable."); ResponseParam(r => r.MusicBrainzArtistId, "The MusicBrainz identifier of the artist, if applicable."); ResponseParam(r => r.Contributors, "The list of references to the media contributors that make up the artist, each with the role they played."); @@ -400,13 +438,13 @@ public class UpdateArtistEndpointSummary : Summary(r => r.Albums![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album."); ResponseParam(r => r.Albums![0].Metadata!.Tags, "The list of tags of the album."); ResponseParam(r => r.Albums![0].Metadata!.Genres, "The list of genres of the album."); - ResponseParam(r => r.Albums![0].Metadata!.ReleaseType, "The type of the release of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseTypes, "The type of the release of the album."); ResponseParam(r => r.Albums![0].Metadata!.ReleaseStatus, "The status of the release of the album."); ResponseParam(r => r.Albums![0].Metadata!.TotalDiscs, "The number of discs of the release of the album."); ResponseParam(r => r.Albums![0].Metadata!.TotalTracks, "The number of tracks of the release of the album."); ResponseParam(r => r.Albums![0].MediaFormat, "The physical or digital medium of the album, if applicable."); ResponseParam(r => r.Albums![0].Barcode, "The barcode of the album, if applicable."); - ResponseParam(r => r.Albums![0].CatalogNumber, "The catalog number of the album, if applicable."); + ResponseParam(r => r.Albums![0].CatalogNumbers, "The catalog numbers of the album, if applicable."); ResponseParam(r => r.Albums![0].MusicBrainzReleaseId, "The MusicBrainz identifier of the release, if applicable."); ResponseParam(r => r.Albums![0].MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group, if applicable."); ResponseParam(r => r.Albums![0].MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist, if applicable."); @@ -451,10 +489,10 @@ public class UpdateArtistEndpointSummary : Summary(r => r.Albums![0].Tracks![0].Script, "The script used by the language of the track, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].Key, "The musical key of the track, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].Bpm, "The tempo of the track in beats per minute, if applicable."); - ResponseParam(r => r.Albums![0].Tracks![0].Work, "The title of the work the track is a recording of, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].Work!.Title, "The title of the work the track is a recording of, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].MusicBrainzRecordingId, "The MusicBrainz identifier of the recording, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].MusicBrainzTrackId, "The MusicBrainz identifier of the track, if applicable."); - ResponseParam(r => r.Albums![0].Tracks![0].MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].CreatedOnUtc, "The date and time when the track was created."); ResponseParam(r => r.Albums![0].Tracks![0].UpdatedOnUtc, "The date and time when the track was last updated, if applicable."); ResponseParam(r => r.Albums![0].Tracks![0].Moods, "The list of moods of the track."); @@ -472,29 +510,49 @@ public class UpdateArtistEndpointSummary : Summary r.Path, "The file system path of the track. Required."); @@ -150,10 +157,10 @@ public class AddTrackEndpointSummary : Summary r.Script, "The script used by the language of the track. Optional."); RequestParam(r => r.Key, "The musical key of the track. Optional."); RequestParam(r => r.Bpm, "The tempo of the track in beats per minute. Optional."); - RequestParam(r => r.Work, "The title of the work the track is a recording of. Optional."); + RequestParam(r => r.Work!.Title, "The title of the work the track is a recording of. Optional."); RequestParam(r => r.MusicBrainzRecordingId, "The MusicBrainz identifier of the recording. Optional."); RequestParam(r => r.MusicBrainzTrackId, "The MusicBrainz identifier of the track. Optional."); - RequestParam(r => r.MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional."); + RequestParam(r => r.Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional."); RequestParam(r => r.Moods, "The list of moods of the track. Optional."); RequestParam(r => r.Isrcs, "The list of ISRC (International Standard Recording Code) of the track. Optional."); RequestParam(r => r.Contributors, "The list of media contributors that performed on the track. Required."); @@ -171,10 +178,10 @@ public class AddTrackEndpointSummary : Summary(r => r.Script, "The script used by the language of the track, if applicable."); ResponseParam(r => r.Key, "The musical key of the track, if applicable."); ResponseParam(r => r.Bpm, "The tempo of the track in beats per minute, if applicable."); - ResponseParam(r => r.Work, "The title of the work the track is a recording of, if applicable."); + ResponseParam(r => r.Work!.Title, "The title of the work the track is a recording of, if applicable."); ResponseParam(r => r.MusicBrainzRecordingId, "The MusicBrainz identifier of the recording, if applicable."); ResponseParam(r => r.MusicBrainzTrackId, "The MusicBrainz identifier of the track, if applicable."); - ResponseParam(r => r.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); + ResponseParam(r => r.Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the track was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the track was last updated, if applicable."); ResponseParam(r => r.Moods, "The list of moods of the track."); @@ -208,15 +215,16 @@ public class AddTrackEndpointSummary : Summary ResponseParam(r => r.Script, "The script used by the language of the track, if applicable."); ResponseParam(r => r.Key, "The musical key of the track, if applicable."); ResponseParam(r => r.Bpm, "The tempo of the track in beats per minute, if applicable."); - ResponseParam(r => r.Work, "The title of the work the track is a recording of, if applicable."); + ResponseParam(r => r.Work!.Title, "The title of the work the track is a recording of, if applicable."); ResponseParam(r => r.MusicBrainzRecordingId, "The MusicBrainz identifier of the recording, if applicable."); ResponseParam(r => r.MusicBrainzTrackId, "The MusicBrainz identifier of the track, if applicable."); - ResponseParam(r => r.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); + ResponseParam(r => r.Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the track was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the track was last updated, if applicable."); ResponseParam(r => r.Moods, "The list of moods of the track."); @@ -78,15 +78,16 @@ public class GetTrackEndpointSummary : Summary AlbumId: Guid.NewGuid(), LibraryId: Guid.NewGuid(), Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", - Metadata: new AudioMetadataDto( + Metadata: new MusicTrackMetadataDto( 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 ReleaseInfoDto( OriginalReleaseDate: new DateOnly(1975, 10, 31), OriginalReleaseYear: 1975, - ReReleaseDate: default, - ReReleaseYear: default, + ReReleaseDate: new DateOnly(2011, 11, 21), + ReReleaseYear: 2011, ReleaseCountry: ReleaseCountry.GB, ReleaseVersion: "Original" ), @@ -113,26 +114,28 @@ public class GetTrackEndpointSummary : Summary Channels: 2, BitDepth: 16, AudioCodec: "FLAC", - Bitrate: 980 + Bitrate: 980, + IsVideo: false ), - TrackNumber: 1, - DiscNumber: 1, Script: "Latn", Key: MusicKey.CMajor, Bpm: 72, - Work: "Bohemian Rhapsody", - MusicBrainzRecordingId: Guid.NewGuid(), - MusicBrainzTrackId: Guid.NewGuid(), - MusicBrainzWorkId: Guid.NewGuid(), - CreatedOnUtc: DateTime.UtcNow, - UpdatedOnUtc: DateTime.UtcNow, + 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 IsrcDto(Value: "GBUM71029604") + ], Moods: [ new MoodDto(Name: "dramatic"), new MoodDto(Name: "anxious") ], - Isrcs: [ - new IsrcDto(Value: "GBUM71029604") - ], + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), Contributors: [ new MediaContributorReferenceDto( ContributorId: Guid.NewGuid(), @@ -156,7 +159,11 @@ public class GetTrackEndpointSummary : Summary 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) ) ); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs index 300f67a3..e873a6d6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs @@ -32,10 +32,11 @@ public class UpdateTrackEndpointSummary : Summary r.Path, "The file system path of the track. Required."); @@ -150,10 +157,10 @@ public class UpdateTrackEndpointSummary : Summary r.Script, "The script used by the language of the track. Optional."); RequestParam(r => r.Key, "The musical key of the track. Optional."); RequestParam(r => r.Bpm, "The tempo of the track in beats per minute. Optional."); - RequestParam(r => r.Work, "The title of the work the track is a recording of. Optional."); + RequestParam(r => r.Work!.Title, "The title of the work the track is a recording of. Optional."); RequestParam(r => r.MusicBrainzRecordingId, "The MusicBrainz identifier of the recording. Optional."); RequestParam(r => r.MusicBrainzTrackId, "The MusicBrainz identifier of the track. Optional."); - RequestParam(r => r.MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional."); + RequestParam(r => r.Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional."); RequestParam(r => r.Moods, "The list of moods of the track. Optional."); RequestParam(r => r.Isrcs, "The list of ISRC (International Standard Recording Code) of the track. Optional."); RequestParam(r => r.Contributors, "The list of media contributors that performed on the track. Required."); @@ -171,10 +178,10 @@ public class UpdateTrackEndpointSummary : Summary(r => r.Script, "The script used by the language of the track, if applicable."); ResponseParam(r => r.Key, "The musical key of the track, if applicable."); ResponseParam(r => r.Bpm, "The tempo of the track in beats per minute, if applicable."); - ResponseParam(r => r.Work, "The title of the work the track is a recording of, if applicable."); + ResponseParam(r => r.Work!.Title, "The title of the work the track is a recording of, if applicable."); ResponseParam(r => r.MusicBrainzRecordingId, "The MusicBrainz identifier of the recording, if applicable."); ResponseParam(r => r.MusicBrainzTrackId, "The MusicBrainz identifier of the track, if applicable."); - ResponseParam(r => r.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); + ResponseParam(r => r.Work!.MusicBrainzWorkId, "The MusicBrainz identifier of the work, if applicable."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the track was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the track was last updated, if applicable."); ResponseParam(r => r.Moods, "The list of moods of the track."); @@ -208,15 +215,16 @@ public class UpdateTrackEndpointSummary : Summary r.Title, "The title of the media library. Required."); @@ -48,6 +49,7 @@ public class AddLibraryEndpointSummary : Summary r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional."); + RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); ResponseParam(r => r.Id, "The unique identifier of the entity."); ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); @@ -60,6 +62,7 @@ public class AddLibraryEndpointSummary : Summary(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -76,6 +79,7 @@ public class AddLibraryEndpointSummary : Summary(r => r.Id, "The unique identifier of the entity."); + ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); + ResponseParam(r => r.Title, "The title of the media library."); + ResponseParam(r => r.LibraryType, "The type of the media library."); + ResponseParam(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located."); + ResponseParam(r => r.CoverImage, "The path of the image file used as the cover for the library."); + ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); + ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); + ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); + ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); + Response(200, "The media libraries are returned.", example: new LibraryResponse[] { new ( @@ -36,6 +51,7 @@ public class GetEnabledLibrariesEndpointSummary : Summary(r => r.Id, "The unique identifier of the entity."); + ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); + ResponseParam(r => r.Title, "The title of the media library."); + ResponseParam(r => r.LibraryType, "The type of the media library."); + ResponseParam(r => r.ContentLocations, "The file system paths of the directories where the media library elements are located."); + ResponseParam(r => r.CoverImage, "The path of the image file used as the cover for the library."); + ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); + ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); + ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); + ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); + Response(200, "The media libraries are returned.", example: new LibraryResponse[] { new ( @@ -36,6 +51,7 @@ public class GetLibrariesEndpointSummary : Summary(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -56,6 +57,7 @@ public class GetLibraryEndpointSummary : Summary +/// API endpoint for the /libraries/path-template-parts/{libraryType} route. +/// +public class GetLibraryPathTemplatePartsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getLibraryPathTemplatePartsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library path template parts queries. + public GetLibraryPathTemplatePartsEndpoint(IQueryHandler> getLibraryPathTemplatePartsQueryHandler) + { + _getLibraryPathTemplatePartsQueryHandler = getLibraryPathTemplatePartsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_PATH_TEMPLATE_PARTS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the path parts available for a media library type. + /// + /// The request containing the media library type whose available path parts are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryPathTemplatePartsRequest request, CancellationToken cancellationToken) + { + Result result = await _getLibraryPathTemplatePartsQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointSummary.cs index d6cc49d1..3f768d70 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointSummary.cs @@ -38,7 +38,8 @@ public class UpdateLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library. Required."); @@ -52,6 +53,7 @@ public class UpdateLibraryEndpointSummary : Summary r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional."); + RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); ResponseParam(r => r.Id, "The unique identifier of the entity."); ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); @@ -64,6 +66,7 @@ public class UpdateLibraryEndpointSummary : Summary(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); + ResponseParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -80,6 +83,7 @@ public class UpdateLibraryEndpointSummary : Summary r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Required."); RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required."); RequestParam(r => r.IsThemeCachingEnabled, "Whether the theme data served to this user is cached, or not. Required."); + RequestParam(r => r.ShouldAggregateMetadataWhenMissing, "Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required."); + RequestParam(r => r.ShouldAggregateArtworkWhenMissing, "Whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. Required."); RequestParam(r => r.ShouldRenderPdfAsImages, "Whether PDF books are rendered as page images for the user, or not. Required."); RequestParam(r => r.ShouldPreserveBookStyles, "Whether the styles of the book content are preserved when it is rendered for the user, or not. Required."); diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 811b1de9..73d8fe89 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -109,6 +109,7 @@ public class Program { ILogger logger = services.GetRequiredService>(); logger.LogCritical(ex, "Failed to run database migrations"); + throw; } } diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs index 574d7c33..69d1d494 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs @@ -67,4 +67,9 @@ public class LibraryDto /// which does not change when the contents of an existing file are edited, and such edits could be missed while this setting is enabled. /// public bool ShouldSkipUnchangedDirectoriesDuringScan { get; set; } = false; + + /// + /// Gets or sets the ordered parts of the template describing the structure of the media library on disk. + /// + public List PathTemplateParts { get; set; } = []; } diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathPartDefinitionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathPartDefinitionDto.cs new file mode 100644 index 00000000..b7300ea5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathPartDefinitionDto.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Libraries; + +/// +/// Data transfer object for a path part available for a media library type. +/// +[DebuggerDisplay("Kind: {Kind}")] +public class LibraryPathPartDefinitionDto +{ + /// + /// Gets or sets the kind of the path part. + /// + public string Kind { get; set; } = string.Empty; + + /// + /// Gets or sets the value type captured by the path part. + /// + public string ValueType { get; set; } = string.Empty; + + /// + /// Gets or sets the default representation of the path part. + /// + public string DefaultRepresentation { get; set; } = string.Empty; + + /// + /// Gets or sets whether the path part is optional by default. + /// + public bool IsOptionalByDefault { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathTemplateCatalogDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathTemplateCatalogDto.cs new file mode 100644 index 00000000..9e2c9509 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathTemplateCatalogDto.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Libraries; + +/// +/// Data transfer object for the path template catalog of a media library type. +/// +[DebuggerDisplay("Parts: {Parts.Count}; DefaultTemplateParts: {DefaultTemplateParts.Count}")] +public class LibraryPathTemplateCatalogDto +{ + /// + /// Gets or sets the path parts that can be used in the path template of the library type. + /// + public List Parts { get; set; } = []; + + /// + /// Gets or sets the ordered parts of the default path template of the library type. + /// + public List DefaultTemplateParts { get; set; } = []; +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathTemplatePartDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathTemplatePartDto.cs new file mode 100644 index 00000000..ef68c908 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryPathTemplatePartDto.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Libraries; + +/// +/// Data transfer object for one part of the path template of a media library. +/// +[DebuggerDisplay("Kind: {Kind}; Representation: {Representation}")] +public class LibraryPathTemplatePartDto +{ + /// + /// Gets or sets the kind of the path part. + /// + public string Kind { get; set; } = string.Empty; + + /// + /// Gets or sets the literal text or the value mask of the path part. + /// + public string Representation { get; set; } = string.Empty; + + /// + /// Gets or sets whether the path part can be absent from the path. + /// + public bool IsOptional { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs index 01e56548..4290cf87 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs @@ -41,6 +41,11 @@ public class UserSettingsDto /// public bool ShouldAggregateMetadataWhenMissing { get; set; } + /// + /// Gets or sets whether the artwork of the media library items is aggregated from multiple providers, when it is missing, or not. + /// + public bool ShouldAggregateArtworkWhenMissing { get; set; } + /// /// Gets or sets whether PDF books are rendered as page images for the user, or not. Rendering PDFs as images preserves the /// original layout, but the pages are not selectable or searchable, unlike their text layer. diff --git a/src/Lumina.Presentation.Web/Common/Enums/Common/ReleaseCountry.cs b/src/Lumina.Presentation.Web/Common/Enums/Common/ReleaseCountry.cs index c989ec33..bce40470 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/Common/ReleaseCountry.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/Common/ReleaseCountry.cs @@ -2,7 +2,7 @@ namespace Lumina.Presentation.Web.Common.Enums.Common; /// -/// Enumeration for the country of a media release, using the ISO 3166-1 alpha-2 country codes. +/// Enumeration for the country of a media release, using the ISO 3166-1 alpha-2 country codes, together with the MusicBrainz special codes for releases issued across Europe or worldwide. /// public enum ReleaseCountry { @@ -984,5 +984,20 @@ public enum ReleaseCountry /// /// The ISO 3166-1 alpha-2 code of Zimbabwe. /// - ZW + ZW, + + /// + /// The ISO 3166-1 alpha-2 code of the Netherlands Antilles, withdrawn in 2010. + /// + AN, + + /// + /// The MusicBrainz code for a release issued across Europe. + /// + XE, + + /// + /// The MusicBrainz code for a release issued worldwide. + /// + XW } diff --git a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs index 5f033276..d7dd6298 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs @@ -23,5 +23,10 @@ public enum ScheduledTaskType /// /// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions. /// - CleanScheduledJobExecutionHistory + CleanScheduledJobExecutionHistory, + + /// + /// The scheduled job cleans the technical data that is no longer valid. + /// + TechnicalDataCleanup } diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequest.cs new file mode 100644 index 00000000..978d481a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents the request for retrieving the path parts available for a media library type. +/// +/// The media library type whose available path parts are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryPathTemplatePartsRequest( + string LibraryType +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs index 63f358f4..64ebcdc6 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs @@ -21,6 +21,7 @@ public static partial class ApiRoutes public const string GET_RUNNING_LIBRARIES_SCAN = "libraries/scans/running"; public const string CANCEL_LIBRARIES_SCAN = "libraries/scans/cancel"; public const string CANCEL_LIBRARY_SCAN = "libraries/{libraryId}/scans/{scanId}/cancel"; + public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "libraries/path-template-parts/{libraryType}"; public const string GET_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers"; public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; public const string REORDER_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers/reorder"; diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs index dd582a50..d89cf6a3 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs @@ -22,6 +22,7 @@ public static partial class WebRoutes public const string SCAN_LIBRARY = "{culture}/libraries/manage/api-scan-library/{id}"; public const string CANCEL_LIBRARIES_SCAN = "{culture}/libraries/manage/api-cancel-libraries-scan"; public const string CANCEL_LIBRARY_SCAN = "{culture}/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"; + public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "{culture}/libraries/manage/api-get-path-template-parts/{libraryType}"; public const string GET_METADATA_PROVIDERS = "{culture}/libraries/manage/api-get-metadata-providers/{libraryId}"; public const string SET_METADATA_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-metadata-provider-enabled"; public const string REORDER_METADATA_PROVIDERS = "{culture}/libraries/manage/api-reorder-metadata-providers"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpoint.cs new file mode 100644 index 00000000..658ef01f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-path-template-parts/{libraryType} route. +/// +public class GetLibraryPathTemplatePartsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibraryPathTemplatePartsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_LIBRARY_PATH_TEMPLATE_PARTS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the path parts available for a media library type. + /// + /// The request containing the media library type whose available path parts are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryPathTemplatePartsRequest request, CancellationToken cancellationToken) + { + LibraryPathTemplateCatalogDto response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_PATH_TEMPLATE_PARTS.Replace("{libraryType}", request.LibraryType), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx index 8cd2978e..25470ea5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx @@ -165,6 +165,9 @@ تنظيف سجل الوظائف + + تنظيف البيانات التقنية + عند بدء التشغيل diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx index 6caf3884..0b2904e1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx @@ -165,6 +165,9 @@ Jobverlauf bereinigen + + Technische Datenbereinigung + Beim Start diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx index 24fa61bb..7bd2a9ee 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx @@ -165,6 +165,9 @@ Clean job history + + Technical data cleanup + At startup diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx index 0a45962c..04a5cc5a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx @@ -165,6 +165,9 @@ Limpiar historial de trabajos + + Limpieza de datos técnicos + Al inicio diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx index bc2a145d..507517ef 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx @@ -165,6 +165,9 @@ Nettoyer l'historique des tâches + + Nettoyage des données techniques + Au démarrage diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx index bc5520f8..dcbbffcb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx @@ -165,6 +165,9 @@ Pulisci la cronologia dei processi + + Pulizia dei dati tecnici + All'avvio diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx index efe836d0..5c1c50c4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx @@ -165,6 +165,9 @@ ジョブ履歴を削除 + + 技術データのクリーンアップ + 起動時 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx index 24fa61bb..7bd2a9ee 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx @@ -165,6 +165,9 @@ Clean job history + + Technical data cleanup + At startup diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx index abd5a9b4..3e2226ee 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx @@ -165,6 +165,9 @@ Curăță istoricul proceselor + + Curățare date tehnice + La pornire diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx index 1feacdb6..9f59af4b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx @@ -165,6 +165,9 @@ Очистити історію завдань + + Очищення технічних даних + Під час запуску diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx index 8aed079b..ff07b5c6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx @@ -165,6 +165,9 @@ 清理作业历史 + + 技术数据清理 + 启动时 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx index 05110f11..4d546005 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ar-SA.resx @@ -189,6 +189,9 @@ إثراء البيانات الوصفية... + + استخراج البيانات الوصفية... + تجزئة محتويات الملفات... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx index ea60c1a2..93d2db81 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx @@ -189,6 +189,9 @@ Metadaten werden angereichert... + + Metadaten werden extrahiert... + Berechne die Datei-Hashes... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx index b772f4af..844849bc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx @@ -189,6 +189,9 @@ Enriching metadata... + + Extracting metadata... + Hashing file contents... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx index b91da2a4..5059ef16 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx @@ -189,6 +189,9 @@ Enriqueciendo metadatos... + + Extrayendo metadatos... + Calculando los hashes de los archivos... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx index d8b63ab0..c3cf79e8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx @@ -189,6 +189,9 @@ Enrichissement des métadonnées... + + Extraction des métadonnées... + Calcul des hachages des fichiers... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx index b8cdd83a..1e6c8f19 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx @@ -189,6 +189,9 @@ Arricchimento dei metadati... + + Estrazione dei metadati... + Calcolo degli hash dei file... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx index d9b01cb4..1ceebafa 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx @@ -189,6 +189,9 @@ メタデータを補完しています... + + メタデータを抽出しています... + ファイルのハッシュを計算中... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx index b772f4af..844849bc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx @@ -189,6 +189,9 @@ Enriching metadata... + + Extracting metadata... + Hashing file contents... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx index dd574f10..c34fc20d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx @@ -189,6 +189,9 @@ Se îmbogățesc metadatele... + + Se extrag metadatele... + Se calculează hash-urile fișierelor... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx index 49cec819..16135874 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx @@ -189,6 +189,9 @@ Збагачення метаданих... + + Видобування метаданих... + Обчислення хешів файлів... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx index 7fe4fc70..349cb9fc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx @@ -189,6 +189,9 @@ 正在丰富元数据... + + 正在提取元数据... + 正在计算文件哈希... diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx index 741a2000..d02b272f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx @@ -1,4 +1,4 @@ - + -
+
+
@@ -34,7 +34,7 @@

@_localizer["GeneralInformation"]

- +
@@ -45,7 +45,7 @@
@_localizer["DescriptionTitle"]
- +
@@ -77,25 +77,25 @@
@_localizer["Movie"]
@_localizer["FilmSeries"]
@_localizer["FilmFranchise"]
-
@_localizer["Concert"]
+
@_localizer["Concert"]
@_localizer["Documentary"]
-
@_localizer["Tutorial"]
-
@_localizer["Personal"]
+
@_localizer["Tutorial"]
+
@_localizer["Personal"]
@_localizer["Anime"]
-
@_localizer["Youtube"]
-
@_localizer["Videoclip"]
+
@_localizer["Youtube"]
+
@_localizer["Videoclip"]
@_localizer["AudioContent"]
@_localizer["Music"]
-
@_localizer["AudioBook"]
-
@_localizer["LivePerformance"]
-
@_localizer["Interview"]
-
@_localizer["Cover"]
+
@_localizer["AudioBook"]
+
@_localizer["LivePerformance"]
+
@_localizer["Interview"]
+
@_localizer["Cover"]
@_localizer["Remix"]
-
@_localizer["Soundeffect"]
-
@_localizer["Podcast"]
+
@_localizer["Soundeffect"]
+
@_localizer["Podcast"]
@_localizer["RadioShow"]
@_localizer["VisualContent"]
-
@_localizer["PhotoAlbum"]
+
@_localizer["PhotoAlbum"]
@_localizer["MiscellaneousContent"]
@_localizer["Other"]
@@ -103,7 +103,7 @@
@_localizer["DescriptionLibraryType"]
- +
: @@ -122,7 +122,7 @@
@_localizer["DescriptionCover"]
- +
@@ -204,6 +204,38 @@
@_localizer["DescriptionShouldSkipUnchangedDirectoriesDuringScan"]
+ + + + @if (id is not null) {

@_localizer["MetadataProviders"]

@@ -217,7 +249,7 @@ - + @_localizer["DescriptionMetadataProviders"] @@ -233,7 +265,7 @@ - + @_localizer["DescriptionArtworkProviders"] @@ -249,7 +281,7 @@ - + @_localizer["DescriptionBookReaders"] @@ -260,7 +292,7 @@
- +
@@ -307,7 +339,15 @@ IsLocked: chkIsLocked.checked, CanDownloadMetadataFromWeb: chkCanDownloadMetadataFromWeb.checked, ShouldSaveMetadataInMediaDirectories: chkShouldSaveMetadataInMediaDirectories.checked, - ShouldSkipUnchangedDirectoriesDuringScan: chkShouldSkipUnchangedDirectoriesDuringScan.checked + ShouldSkipUnchangedDirectoriesDuringScan: chkShouldSkipUnchangedDirectoriesDuringScan.checked, + PathTemplateParts: Array.from(pathTemplateDropzone.querySelectorAll('.path-template-pill')).map(pill => { + const optional = pill.querySelector('.path-template-optional'); + return { + Kind: pill.dataset.kind, + Representation: getPathTemplatePillRepresentation(pill), + IsOptional: optional ? optional.checked : false + }; + }) }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SAVE_LIBRARY)', formData); if (data) { @@ -404,7 +444,7 @@ async function loadMetadataProvidersAsync() { if (!id || !metadataProvidersTbody) return; const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_METADATA_PROVIDERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. + .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. const response = await callApiGetAsync(url); if (response && response.length > 0) { metadataProvidersTbody.innerHTML = response.map((provider, index) => renderMetadataProviderRow(provider, index, response.length)).join(''); @@ -475,7 +515,7 @@ async function loadArtworkProvidersAsync() { if (!id || !artworkProvidersTbody) return; const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. + .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. const response = await callApiGetAsync(url); if (response && response.length > 0) { artworkProvidersTbody.innerHTML = response.map((provider, index) => renderArtworkProviderRow(provider, index, response.length)).join(''); @@ -546,7 +586,7 @@ async function loadBookReadersAsync() { if (!id || !bookReadersTbody) return; const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_BOOK_READERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. + .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. const response = await callApiGetAsync(url); if (response && response.length > 0) { bookReadersTbody.innerHTML = response.map(reader => renderBookReaderRow(reader)).join(''); @@ -582,6 +622,340 @@ } }; + // Path template editor. + const pathTemplateSection = document.getElementById('path-template-section'); + const pathTemplatePalette = document.getElementById('path-template-palette'); + const pathTemplateDropzone = document.getElementById('path-template-dropzone'); + const pathTemplatePreviewValue = document.getElementById('path-template-preview-value'); + const libraryTypeSelectedItem = document.getElementById('library-selected-item'); + // The type the library was loaded with, so that the saved template is only restored for it, and not when the user previews other types. + const initialLibraryType = libraryTypeSelectedItem ? libraryTypeSelectedItem.getAttribute('data-value') : null; + const libraryTypeDropdown = form.querySelector('.enlightenment-combobox .enlightenment-dropdown'); + const pathSeparator = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(System.IO.Path.DirectorySeparatorChar.ToString())); + const savedPathTemplateParts = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.PathTemplateParts, new System.Text.Json.JsonSerializerOptions { PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase })); + // The localized strings used inside this script must be injected as JSON, not as raw HTML text: Razor HTML-encodes non-ASCII + // characters into numeric entities (e.g. "ă" becomes "ă"), and the browser does not decode entities inside a + // script element, so they would show up literally. JSON escapes them as \uXXXX, which the script reads correctly. + const pathPartLabels = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(new System.Collections.Generic.Dictionary + { + ["Literal"] = _localizer["PathPartLiteral"].Value, + ["Separator"] = _localizer["PathPartSeparator"].Value, + ["Artist"] = _localizer["PathPartArtist"].Value, + ["ReleaseType"] = _localizer["PathPartReleaseType"].Value, + ["ReleaseYear"] = _localizer["PathPartReleaseYear"].Value, + ["ReleaseName"] = _localizer["PathPartReleaseName"].Value, + ["TrackNumber"] = _localizer["PathPartTrackNumber"].Value, + ["TrackName"] = _localizer["PathPartTrackName"].Value, + ["Extension"] = _localizer["PathPartExtension"].Value, + ["DiscNumber"] = _localizer["PathPartDiscNumber"].Value, + ["Author"] = _localizer["PathPartAuthor"].Value, + ["Title"] = _localizer["PathPartTitle"].Value, + ["Series"] = _localizer["PathPartSeries"].Value, + ["SeriesNumber"] = _localizer["PathPartSeriesNumber"].Value, + ["BookId"] = _localizer["PathPartBookId"].Value + })); + const pathTemplateStrings = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(new System.Collections.Generic.Dictionary + { + ["optional"] = _localizer["PathPartOptional"].Value, + ["remove"] = _localizer["Remove"].Value, + ["literal"] = _localizer["PathPartLiteralPlaceholder"].Value, + ["digits"] = _localizer["PathPartDigits"].Value + })); + // The preview shows an example path built from a real example of each library type, so the user sees the effect of the template. + const pathTemplateSamples = { + Music: { + Artist: 'QUEEN', + ReleaseType: 'Album', + ReleaseYear: '1975', + ReleaseName: 'A night at the opera', + TrackNumber: '11', + TrackName: 'Bohemian rhapsody', + DiscNumber: '1', + Extension: 'mp3' + }, + Book: { + Author: 'J. R. R. Tolkien', + Title: 'The Fellowship of the Ring', + Series: 'The Lord of the Rings', + SeriesNumber: '1', + BookId: '42', + Extension: 'epub' + } + }; + let currentPathTemplateSample = {}; + const pathTemplateCatalogCache = {}; + const pathPartValueTypes = {}; + let draggedPathTemplatePill = null; + + // Gets the localized display name of a path part kind. + function pathTemplateKindLabel(kind) { + return pathPartLabels[kind] || kind; + } + + // Parses a value mask like "Disc {0:00}" into its literal prefix, digit width, and literal suffix. + function parsePathTemplateMask(representation) { + const match = (representation || '').match(/^(.*)\{0(?::(0+))?\}(.*)$/); + if (!match) + return { prefix: representation || '', width: 0, suffix: '' }; + return { prefix: match[1], width: match[2] ? match[2].length : 0, suffix: match[3] }; + } + + // Rebuilds a value mask from its literal prefix, digit width, and literal suffix. + function buildPathTemplateMask(prefix, width, suffix) { + return (prefix || '') + '{0' + (width > 0 ? ':' + '0'.repeat(width) : '') + '}' + (suffix || ''); + } + + // Creates an editable pill for one part of the path template, as it is placed in the drop zone. + function renderPathTemplatePill(part) { + const pill = document.createElement('div'); + pill.className = 'path-template-pill'; + pill.setAttribute('draggable', 'true'); + pill.dataset.kind = part.kind; + pill.title = pathTemplateKindLabel(part.kind); + + // The human readable name of the part, so the user knows what each pill means. + const label = document.createElement('span'); + label.className = 'path-template-part-label'; + label.textContent = pathTemplateKindLabel(part.kind); + pill.appendChild(label); + + if (part.kind === 'Separator') { + // A folder separator is shown as its own glyph, never as a raw mask. + const separator = document.createElement('span'); + separator.className = 'path-template-separator-chip'; + separator.textContent = pathSeparator; + pill.appendChild(separator); + } else if (part.kind === 'Literal') { + // An arbitrary text segment, like the "Disk " glue, is edited directly. + const input = document.createElement('input'); + input.type = 'text'; + input.className = 'enlightenment-input path-template-literal-input'; + input.value = part.representation || ''; + input.placeholder = pathTemplateStrings.literal; + input.addEventListener('input', updatePathTemplatePreview); + pill.appendChild(input); + } else { + // Numeric parts can be told how many digits they always use, so values like "01" are understood. + if (pathPartValueTypes[part.kind] === 'Integer') { + const parsed = parsePathTemplateMask(part.representation); + const widthInput = document.createElement('input'); + widthInput.type = 'number'; + widthInput.min = '0'; + widthInput.max = '10'; + widthInput.className = 'enlightenment-input path-template-width'; + widthInput.value = parsed.width; + widthInput.title = pathTemplateStrings.digits; + widthInput.placeholder = pathTemplateStrings.digits; + widthInput.addEventListener('input', updatePathTemplatePreview); + pill.appendChild(widthInput); + } + } + + const optionalLabel = document.createElement('label'); + optionalLabel.className = 'enlightenment-checkbox-label'; + optionalLabel.title = pathTemplateStrings.optional; + const optionalInput = document.createElement('input'); + optionalInput.type = 'checkbox'; + optionalInput.className = 'enlightenment-checkbox-hidden path-template-optional'; + optionalInput.checked = !!part.isOptional; + optionalInput.addEventListener('change', updatePathTemplatePreview); + const optionalSpan = document.createElement('span'); + optionalSpan.className = 'enlightenment-checkbox'; + optionalLabel.appendChild(optionalInput); + optionalLabel.appendChild(optionalSpan); + pill.appendChild(optionalLabel); + const remove = document.createElement('img'); + remove.src = '/images/ui/delete.svg'; + remove.alt = pathTemplateStrings.remove; + remove.title = pathTemplateStrings.remove; + remove.className = 'path-template-remove'; + remove.addEventListener('click', () => { pill.remove(); updatePathTemplatePreview(); }); + pill.appendChild(remove); + pill.addEventListener('dragstart', (e) => { + draggedPathTemplatePill = pill; + e.dataTransfer.effectAllowed = 'move'; + e.dataTransfer.setData('text/plain', 'pill'); + }); + pill.addEventListener('dragend', () => { draggedPathTemplatePill = null; clearPathTemplateDropIndicator(); }); + return pill; + } + + // Builds the stored representation mask of a pill from its human friendly editors. + function getPathTemplatePillRepresentation(pill) { + const kind = pill.dataset.kind; + if (kind === 'Separator') + return ''; + if (kind === 'Literal') { + const input = pill.querySelector('.path-template-literal-input'); + return input ? input.value : ''; + } + const width = pill.querySelector('.path-template-width'); + return buildPathTemplateMask('', width ? Math.max(0, parseInt(width.value || '0', 10)) : 0, ''); + } + + // Replaces the parts in the drop zone with the provided parts. + function renderPathTemplateParts(parts) { + if (!pathTemplateDropzone) return; + pathTemplateDropzone.innerHTML = ''; + (parts || []).forEach(part => pathTemplateDropzone.appendChild(renderPathTemplatePill(part))); + updatePathTemplatePreview(); + } + + // Renders the palette of the parts that can be added to the path template. + function renderPathTemplatePalette(parts) { + if (!pathTemplatePalette) return; + pathTemplatePalette.innerHTML = ''; + (parts || []).forEach(definition => { + const pill = document.createElement('div'); + pill.className = 'path-template-palette-pill'; + pill.setAttribute('draggable', 'true'); + pill.textContent = pathTemplateKindLabel(definition.kind); + pill.addEventListener('dragstart', (e) => { + e.dataTransfer.effectAllowed = 'copy'; + e.dataTransfer.setData('application/json', JSON.stringify({ + source: 'palette', + kind: definition.kind, + representation: definition.defaultRepresentation, + isOptional: definition.isOptionalByDefault + })); + }); + pathTemplatePalette.appendChild(pill); + }); + } + + // Formats the sample value of a part according to its mask, for the preview. + function formatPathTemplateValue(representation, value) { + const match = representation.match(/\{0(?::(0+))?\}/); + if (!match) + return representation + value; + const formatted = match[1] ? String(value).padStart(match[1].length, '0') : value; + return representation.slice(0, match.index) + formatted + representation.slice(match.index + match[0].length); + } + + // Rebuilds the preview path from the pills currently in the drop zone. + function updatePathTemplatePreview() { + if (!pathTemplatePreviewValue || !pathTemplateDropzone) return; + let result = ''; + pathTemplateDropzone.querySelectorAll('.path-template-pill').forEach(pill => { + const kind = pill.dataset.kind; + if (kind === 'Separator') { result += pathSeparator; return; } + const representation = getPathTemplatePillRepresentation(pill); + if (kind === 'Literal') { result += representation; return; } + result += formatPathTemplateValue(representation, currentPathTemplateSample[kind] || ''); + }); + pathTemplatePreviewValue.textContent = result; + } + + // Loads the path template catalog of the selected library type, and the template to display in the editor. + async function loadPathTemplateAsync() { + if (!libraryTypeSelectedItem || !pathTemplateDropzone) return; + const libraryType = libraryTypeSelectedItem.getAttribute('data-value'); + if (!libraryType) return; + currentPathTemplateSample = pathTemplateSamples[libraryType] || {}; + let catalog = pathTemplateCatalogCache[libraryType]; + if (!catalog) { + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_LIBRARY_PATH_TEMPLATE_PARTS, new { libraryType = "Music" })'.replace('/Music', `/${libraryType}`); + catalog = await callApiGetAsync(url); + if (!catalog) catalog = { parts: [], defaultTemplateParts: [] }; + pathTemplateCatalogCache[libraryType] = catalog; + } + // Only library types that define path parts get the editor; the others have no structure to describe. + const hasParts = (catalog.parts || []).length > 0; + if (pathTemplateSection) pathTemplateSection.classList.toggle('hidden', !hasParts); + if (!hasParts) { + renderPathTemplatePalette([]); + renderPathTemplateParts([]); + return; + } + (catalog.parts || []).forEach(definition => { pathPartValueTypes[definition.kind] = definition.valueType; }); + renderPathTemplatePalette(catalog.parts); + // The stored template belongs to the library type it was saved for, so it is only restored for that type. + const parts = (savedPathTemplateParts && savedPathTemplateParts.length > 0 && libraryType === initialLibraryType) + ? savedPathTemplateParts + : catalog.defaultTemplateParts; + renderPathTemplateParts(parts); + } + + // Finds the pill a drag or drop should be placed relative to, based on the pointer position. This also places a part dropped in a + // gap between pills, or anywhere in the drop zone, next to the nearest pill, instead of always sending it to the end. + function getPathTemplateInsertReference(e, excludePill) { + const pills = Array.from(pathTemplateDropzone.querySelectorAll('.path-template-pill')).filter(pill => pill !== excludePill); + if (pills.length === 0) return null; + let nearestPill = null; + let nearestRect = null; + let nearestDistance = Infinity; + for (const pill of pills) { + const rect = pill.getBoundingClientRect(); + const distance = Math.hypot(e.clientX - (rect.left + rect.width / 2), e.clientY - (rect.top + rect.height / 2)); + if (distance < nearestDistance) { + nearestDistance = distance; + nearestPill = pill; + nearestRect = rect; + } + } + return { pill: nearestPill, placeAfter: e.clientX > (nearestRect.left + nearestRect.width / 2) }; + } + + // Removes the insertion indicator from all pills. + function clearPathTemplateDropIndicator() { + pathTemplateDropzone.querySelectorAll('.path-template-pill').forEach(pill => pill.classList.remove('path-template-drop-before', 'path-template-drop-after')); + } + + // Highlights the side of the pill the dragged part would be inserted on. + function updatePathTemplateDropIndicator(e) { + clearPathTemplateDropIndicator(); + const reference = getPathTemplateInsertReference(e, draggedPathTemplatePill); + if (reference) + reference.pill.classList.add(reference.placeAfter ? 'path-template-drop-after' : 'path-template-drop-before'); + } + + // On a drag over the path template drop zone, allows the drop and shows where the part would be inserted. + const handlePathTemplateDragOver = function(e) { + e.preventDefault(); + e.dataTransfer.dropEffect = draggedPathTemplatePill ? 'move' : 'copy'; + updatePathTemplateDropIndicator(e); + }; + + // On a drop over the path template drop zone, inserts a palette part or moves a pill at the pointer position. + const handlePathTemplateDrop = function(e) { + e.preventDefault(); + const reference = getPathTemplateInsertReference(e, draggedPathTemplatePill); + clearPathTemplateDropIndicator(); + const insertAtReference = (pill) => { + if (reference) + reference.pill.insertAdjacentElement(reference.placeAfter ? 'afterend' : 'beforebegin', pill); + else + pathTemplateDropzone.appendChild(pill); + }; + const raw = e.dataTransfer.getData('application/json'); + if (raw) { + const part = JSON.parse(raw); + if (part.source === 'palette') { + insertAtReference(renderPathTemplatePill(part)); + updatePathTemplatePreview(); + return; + } + } + if (draggedPathTemplatePill) { + insertAtReference(draggedPathTemplatePill); + draggedPathTemplatePill = null; + updatePathTemplatePreview(); + } + }; + + // On dragging out of the drop zone, removes the insertion indicator. + const handlePathTemplateDragLeave = function(e) { + if (!pathTemplateDropzone.contains(e.relatedTarget)) + clearPathTemplateDropIndicator(); + }; + + // On selecting another library type, the available parts and the default template change. + const handleLibraryTypeChange = function(e) { + const option = e.target.closest('.enlightenment-option'); + if (!option || option.classList.contains('disabled') || !option.getAttribute('data-value')) return; + setTimeout(() => { loadPathTemplateAsync(); }, 0); + }; + // Add listeners. form.addEventListener('keypress', handleEnterKey); form.addEventListener('submit', handleSubmit); @@ -591,6 +965,10 @@ imgAddCover.addEventListener('click', handleImgAddCoverClick); mediaCoverFormTable.addEventListener('click', handleRowRemoval); mediaDirectoriesFormTable.addEventListener('click', handleRowRemoval); + pathTemplateDropzone.addEventListener('dragover', handlePathTemplateDragOver); + pathTemplateDropzone.addEventListener('drop', handlePathTemplateDrop); + pathTemplateDropzone.addEventListener('dragleave', handlePathTemplateDragLeave); + if (libraryTypeDropdown) libraryTypeDropdown.addEventListener('click', handleLibraryTypeChange); if (metadataProvidersTbody) { metadataProvidersTbody.addEventListener('click', handleMetadataProviderReorderAsync); metadataProvidersTbody.addEventListener('change', handleMetadataProviderEnabledChangeAsync); @@ -613,6 +991,10 @@ imgAddCover.removeEventListener('click', handleImgAddCoverClick); mediaCoverFormTable.removeEventListener('click', handleRowRemoval); mediaDirectoriesFormTable.removeEventListener('click', handleRowRemoval); + pathTemplateDropzone.removeEventListener('dragover', handlePathTemplateDragOver); + pathTemplateDropzone.removeEventListener('drop', handlePathTemplateDrop); + pathTemplateDropzone.removeEventListener('dragleave', handlePathTemplateDragLeave); + if (libraryTypeDropdown) libraryTypeDropdown.removeEventListener('click', handleLibraryTypeChange); if (metadataProvidersTbody) { metadataProvidersTbody.removeEventListener('click', handleMetadataProviderReorderAsync); metadataProvidersTbody.removeEventListener('change', handleMetadataProviderEnabledChangeAsync); @@ -633,6 +1015,9 @@ loadBookReadersAsync(); } + // Load the path template of the selected library type, and its default, for both new and existing libraries. + loadPathTemplateAsync(); + // Store all cleanups for this view on window object using the scriptId. window.viewCleanups = window.viewCleanups || {}; window.viewCleanups['@scriptId'] = () => { diff --git a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml index a4afdc8d..904b8a2d 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml @@ -104,6 +104,32 @@
@_localizer["DescriptionShouldPreserveBookStyles"] + +
+
+ : +
+
+ +
+ @_localizer["DescriptionShouldAggregateMetadataWhenMissing"] +
+ +
+
+ : +
+
+ +
+ @_localizer["DescriptionShouldAggregateArtworkWhenMissing"] +
@@ -126,7 +152,8 @@ const checkboxIsThemeCachingEnabled = document.getElementById('IsThemeCachingEnabled'); const checkboxShouldRenderPdfAsImages = document.getElementById('ShouldRenderPdfAsImages'); const checkboxShouldPreserveBookStyles = document.getElementById('ShouldPreserveBookStyles'); - let shouldAggregateMetadataWhenMissing = false; + const checkboxShouldAggregateMetadataWhenMissing = document.getElementById('ShouldAggregateMetadataWhenMissing'); + const checkboxShouldAggregateArtworkWhenMissing = document.getElementById('ShouldAggregateArtworkWhenMissing'); // Toggle the enabled state of the items per page input based on the pagination checkbox. function updateItemsPerPageEnabledState() { @@ -143,7 +170,8 @@ checkboxIsThemeCachingEnabled.checked = data.isThemeCachingEnabled === true; checkboxShouldRenderPdfAsImages.checked = data.shouldRenderPdfAsImages === true; checkboxShouldPreserveBookStyles.checked = data.shouldPreserveBookStyles === true; - shouldAggregateMetadataWhenMissing = data.shouldAggregateMetadataWhenMissing === true; + checkboxShouldAggregateMetadataWhenMissing.checked = data.shouldAggregateMetadataWhenMissing === true; + checkboxShouldAggregateArtworkWhenMissing.checked = data.shouldAggregateArtworkWhenMissing === true; updateItemsPerPageEnabledState(); } } @@ -155,7 +183,8 @@ ItemsPerPage: Number(inputItemsPerPage.value), ShouldIgnoreThePrefixForAlphaPicker: checkboxShouldIgnoreThePrefixForAlphaPicker.checked, IsThemeCachingEnabled: checkboxIsThemeCachingEnabled.checked, - ShouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing, + ShouldAggregateMetadataWhenMissing: checkboxShouldAggregateMetadataWhenMissing.checked, + ShouldAggregateArtworkWhenMissing: checkboxShouldAggregateArtworkWhenMissing.checked, ShouldRenderPdfAsImages: checkboxShouldRenderPdfAsImages.checked, ShouldPreserveBookStyles: checkboxShouldPreserveBookStyles.checked }; diff --git a/src/Lumina.sln b/src/Lumina.sln index 7aedef91..5d14a1d5 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -1,4 +1,3 @@ - Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -31,25 +30,19 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{19C1EE2F-0F4C-4BF6-B677-E0EC37AB3C72}" ProjectSection(SolutionItems) = preProject - ..\LICENSE.md = ..\LICENSE.md - ..\README.md = ..\README.md ..\docs\CONTRIBUTING.md = ..\docs\CONTRIBUTING.md ..\docs\INSTALL.md = ..\docs\INSTALL.md + ..\LICENSE.md = ..\LICENSE.md + ..\README.md = ..\README.md ..\docs\SOURCES.md = ..\docs\SOURCES.md ..\docs\USAGE.md = ..\docs\USAGE.md EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "technical", "technical", "{64570222-A5AC-49EE-BEBC-25D61B989A20}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "api", "api", "{D78A725D-C3AE-420B-ABA8-255A000D7324}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "admin", "admin", "{459EF701-AB73-40ED-81E6-144D3587C667}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "authorization", "authorization", "{08113205-695B-4DA4-8355-6C5377BBD8C0}" ProjectSection(SolutionItems) = preProject @@ -68,12 +61,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "file-system-management", "f EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "library", "library", "{6A5D3BED-AE4A-4D26-B12A-5DE996152A64}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "audio-library", "audio-library", "{252D7F8D-991F-4C62-9BB1-D13988D7B4E2}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "music-library", "music-library", "{81BD9DAE-9044-41AC-BBC4-1B09EF678D4E}" ProjectSection(SolutionItems) = preProject @@ -88,8 +77,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "written-content-library", "written-content-library", "{2293B76C-F1EB-46A9-8F67-E88BAEA4FC0C}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "book-library", "book-library", "{52264424-9A8F-4E12-9A14-87F306C595C7}" ProjectSection(SolutionItems) = preProject @@ -143,8 +130,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture", "architectur EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-knowledge-management", "architecture-knowledge-management", "{61E7E9B9-3C47-4E62-B49E-AFE8D6DC8B5C}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", "architecture-decision-log", "{095CFEA5-8927-4347-9048-9BE0C8DC7CD0}" ProjectSection(SolutionItems) = preProject @@ -162,6 +147,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md + ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0015.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0015.md EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{3EE8EFDF-4D55-4EA3-BEE2-74D00CB50570}" @@ -181,12 +167,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "requests", "requests", "{B4 EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "admin", "admin", "{48BAE4E1-B3E7-4517-82BF-51D5B884E2E4}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "authorization", "authorization", "{A9BD996E-E8E8-4C34-B792-5E6A00BD5938}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "permissions", "permissions", "{7DC07C5C-4877-45DF-86C2-D93069EA7608}" ProjectSection(SolutionItems) = preProject @@ -203,8 +185,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "roles", "roles", "{3BCFBE37 EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "file-system-management", "file-system-management", "{6D5C6E19-67A1-4327-A958-1EC0DA6E9D7D}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "directories", "directories", "{B6A1AB2C-766F-4DC2-894A-4DF1FE102AED}" ProjectSection(SolutionItems) = preProject @@ -244,16 +224,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "thumbnails", "thumbnails", EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "library", "library", "{38048ADA-6830-4575-BDA6-C6D77E6D3E09}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "audio-library", "audio-library", "{48201A6C-CE2B-47EC-AEC8-C202843D2CEB}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "music-library", "music-library", "{A65199DD-543E-4C18-A16A-215BD34962A5}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "albums", "albums", "{B4DF8E8D-C245-4E7C-B85B-B52935EDA93B}" ProjectSection(SolutionItems) = preProject @@ -294,6 +268,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", ..\docs\technical\requests\library\management\GetEnabledLibraries.http = ..\docs\technical\requests\library\management\GetEnabledLibraries.http ..\docs\technical\requests\library\management\GetLibraries.http = ..\docs\technical\requests\library\management\GetLibraries.http ..\docs\technical\requests\library\management\GetLibrary.http = ..\docs\technical\requests\library\management\GetLibrary.http + ..\docs\technical\requests\library\management\GetLibraryPathTemplateParts.http = ..\docs\technical\requests\library\management\GetLibraryPathTemplateParts.http ..\docs\technical\requests\library\management\GetLibraryScanProgress.http = ..\docs\technical\requests\library\management\GetLibraryScanProgress.http ..\docs\technical\requests\library\management\GetRunningLibraryScans.http = ..\docs\technical\requests\library\management\GetRunningLibraryScans.http ..\docs\technical\requests\library\management\ScanLibraries.http = ..\docs\technical\requests\library\management\ScanLibraries.http @@ -302,12 +277,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "written-content-library", "written-content-library", "{61824D19-B08C-45C6-95F8-716B5FDA183C}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "book-library", "book-library", "{0C975F46-8A47-48EC-91A0-2B222032C043}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "books", "books", "{299D6BD8-A7AC-4913-AA0C-EE0A7AAF5B9A}" ProjectSection(SolutionItems) = preProject @@ -368,8 +339,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scheduling", "scheduling", EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "themes", "themes", "{4EC0F04D-6794-429D-8306-E72C4E64B1D9}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", "{698FA5E0-7220-4A8F-9695-224890B19FC1}" ProjectSection(SolutionItems) = preProject @@ -390,8 +359,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "queries", "queries", "{FB8C EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "users-management", "users-management", "{863E6DFF-B0F3-4CFA-8544-260346A7735A}" - ProjectSection(SolutionItems) = preProject - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "authentication", "authentication", "{0C679328-F15A-46A9-890C-DED45CDE4680}" ProjectSection(SolutionItems) = preProject @@ -445,6 +412,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SecurityTests", "SecurityTe EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.SecurityTests", "..\tests\SecurityTests\Lumina.Presentation.Api.SecurityTests\Lumina.Presentation.Api.SecurityTests.csproj", "{F72DCA2D-0349-42F9-9614-92A38D4B1EA4}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.SecurityTests", "..\tests\SecurityTests\Lumina.Plugins.Calibre.SecurityTests\Lumina.Plugins.Calibre.SecurityTests.csproj", "{E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.CoverArtArchive.SecurityTests", "..\tests\SecurityTests\Lumina.Plugins.CoverArtArchive.SecurityTests\Lumina.Plugins.CoverArtArchive.SecurityTests.csproj", "{C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.MusicBrainz.SecurityTests", "..\tests\SecurityTests\Lumina.Plugins.MusicBrainz.SecurityTests\Lumina.Plugins.MusicBrainz.SecurityTests.csproj", "{D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Contracts", "Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj", "{8CF6FEA4-624C-4EC9-93D6-EB7626059D7C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "plugins", "plugins", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" @@ -517,6 +490,34 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Pdf.Integrat EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.IntegrationTests", "..\tests\IntegrationTests\Lumina.Plugins.Calibre.IntegrationTests\Lumina.Plugins.Calibre.IntegrationTests.csproj", "{319846E2-F97B-4547-9134-59B5D7BB9E2D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.ID3.IntegrationTests", "..\tests\IntegrationTests\Lumina.Plugins.ID3.IntegrationTests\Lumina.Plugins.ID3.IntegrationTests.csproj", "{FD068F9A-5220-4E4C-9A0E-EE774EFA391D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.MusicBrainz", "..\plugins\Lumina.Plugins.MusicBrainz\Lumina.Plugins.MusicBrainz.csproj", "{E00D4FDD-9BDF-4490-8500-8CE0173CC239}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.MusicBrainz.UnitTests", "..\tests\UnitTests\Lumina.Plugins.MusicBrainz.UnitTests\Lumina.Plugins.MusicBrainz.UnitTests.csproj", "{8FE084F4-BD5D-4088-8440-4A9881D4417D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.ID3", "..\plugins\Lumina.Plugins.ID3\Lumina.Plugins.ID3.csproj", "{7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.ID3.UnitTests", "..\tests\UnitTests\Lumina.Plugins.ID3.UnitTests\Lumina.Plugins.ID3.UnitTests.csproj", "{F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.ID3.Fixtures", "..\tests\Common\Lumina.Plugins.ID3.Fixtures\Lumina.Plugins.ID3.Fixtures.csproj", "{BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.MusicBrainz.Fixtures", "..\tests\Common\Lumina.Plugins.MusicBrainz.Fixtures\Lumina.Plugins.MusicBrainz.Fixtures.csproj", "{C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.CoverArtArchive", "..\plugins\Lumina.Plugins.CoverArtArchive\Lumina.Plugins.CoverArtArchive.csproj", "{D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.LocalMusicArtwork", "..\plugins\Lumina.Plugins.LocalMusicArtwork\Lumina.Plugins.LocalMusicArtwork.csproj", "{A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.CoverArtArchive.Fixtures", "..\tests\Common\Lumina.Plugins.CoverArtArchive.Fixtures\Lumina.Plugins.CoverArtArchive.Fixtures.csproj", "{A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.CoverArtArchive.UnitTests", "..\tests\UnitTests\Lumina.Plugins.CoverArtArchive.UnitTests\Lumina.Plugins.CoverArtArchive.UnitTests.csproj", "{F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.LocalMusicArtwork.Fixtures", "..\tests\Common\Lumina.Plugins.LocalMusicArtwork.Fixtures\Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj", "{2220A59B-5BA3-40E1-A03C-52EA800FDB60}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.LocalMusicArtwork.UnitTests", "..\tests\UnitTests\Lumina.Plugins.LocalMusicArtwork.UnitTests\Lumina.Plugins.LocalMusicArtwork.UnitTests.csproj", "{49AA662D-563F-4810-880A-5F5BF7949CC6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.LocalMusicArtwork.IntegrationTests", "..\tests\IntegrationTests\Lumina.Plugins.LocalMusicArtwork.IntegrationTests\Lumina.Plugins.LocalMusicArtwork.IntegrationTests.csproj", "{E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -703,6 +704,42 @@ Global {F72DCA2D-0349-42F9-9614-92A38D4B1EA4}.Release|x64.Build.0 = Release|Any CPU {F72DCA2D-0349-42F9-9614-92A38D4B1EA4}.Release|x86.ActiveCfg = Release|Any CPU {F72DCA2D-0349-42F9-9614-92A38D4B1EA4}.Release|x86.Build.0 = Release|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Debug|x64.ActiveCfg = Debug|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Debug|x64.Build.0 = Debug|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Debug|x86.ActiveCfg = Debug|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Debug|x86.Build.0 = Debug|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Release|Any CPU.Build.0 = Release|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Release|x64.ActiveCfg = Release|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Release|x64.Build.0 = Release|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Release|x86.ActiveCfg = Release|Any CPU + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9}.Release|x86.Build.0 = Release|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Debug|x64.ActiveCfg = Debug|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Debug|x64.Build.0 = Debug|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Debug|x86.ActiveCfg = Debug|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Debug|x86.Build.0 = Debug|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Release|Any CPU.Build.0 = Release|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Release|x64.ActiveCfg = Release|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Release|x64.Build.0 = Release|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Release|x86.ActiveCfg = Release|Any CPU + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7}.Release|x86.Build.0 = Release|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Debug|x64.ActiveCfg = Debug|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Debug|x64.Build.0 = Debug|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Debug|x86.ActiveCfg = Debug|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Debug|x86.Build.0 = Debug|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Release|Any CPU.Build.0 = Release|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Release|x64.ActiveCfg = Release|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Release|x64.Build.0 = Release|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Release|x86.ActiveCfg = Release|Any CPU + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8}.Release|x86.Build.0 = Release|Any CPU {8CF6FEA4-624C-4EC9-93D6-EB7626059D7C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8CF6FEA4-624C-4EC9-93D6-EB7626059D7C}.Debug|Any CPU.Build.0 = Debug|Any CPU {8CF6FEA4-624C-4EC9-93D6-EB7626059D7C}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -1111,11 +1148,190 @@ Global {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|x64.Build.0 = Release|Any CPU {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|x86.ActiveCfg = Release|Any CPU {319846E2-F97B-4547-9134-59B5D7BB9E2D}.Release|x86.Build.0 = Release|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Debug|x64.ActiveCfg = Debug|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Debug|x64.Build.0 = Debug|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Debug|x86.ActiveCfg = Debug|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Debug|x86.Build.0 = Debug|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Release|Any CPU.Build.0 = Release|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Release|x64.ActiveCfg = Release|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Release|x64.Build.0 = Release|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Release|x86.ActiveCfg = Release|Any CPU + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D}.Release|x86.Build.0 = Release|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Debug|x64.ActiveCfg = Debug|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Debug|x64.Build.0 = Debug|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Debug|x86.ActiveCfg = Debug|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Debug|x86.Build.0 = Debug|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Release|Any CPU.Build.0 = Release|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Release|x64.ActiveCfg = Release|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Release|x64.Build.0 = Release|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Release|x86.ActiveCfg = Release|Any CPU + {E00D4FDD-9BDF-4490-8500-8CE0173CC239}.Release|x86.Build.0 = Release|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Debug|x64.ActiveCfg = Debug|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Debug|x64.Build.0 = Debug|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Debug|x86.ActiveCfg = Debug|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Debug|x86.Build.0 = Debug|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Release|Any CPU.Build.0 = Release|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Release|x64.ActiveCfg = Release|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Release|x64.Build.0 = Release|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Release|x86.ActiveCfg = Release|Any CPU + {8FE084F4-BD5D-4088-8440-4A9881D4417D}.Release|x86.Build.0 = Release|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Debug|x64.ActiveCfg = Debug|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Debug|x64.Build.0 = Debug|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Debug|x86.ActiveCfg = Debug|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Debug|x86.Build.0 = Debug|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Release|Any CPU.Build.0 = Release|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Release|x64.ActiveCfg = Release|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Release|x64.Build.0 = Release|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Release|x86.ActiveCfg = Release|Any CPU + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0}.Release|x86.Build.0 = Release|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Debug|x64.ActiveCfg = Debug|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Debug|x64.Build.0 = Debug|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Debug|x86.ActiveCfg = Debug|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Debug|x86.Build.0 = Debug|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Release|Any CPU.Build.0 = Release|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Release|x64.ActiveCfg = Release|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Release|x64.Build.0 = Release|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Release|x86.ActiveCfg = Release|Any CPU + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039}.Release|x86.Build.0 = Release|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Debug|x64.ActiveCfg = Debug|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Debug|x64.Build.0 = Debug|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Debug|x86.ActiveCfg = Debug|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Debug|x86.Build.0 = Debug|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Release|Any CPU.Build.0 = Release|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Release|x64.ActiveCfg = Release|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Release|x64.Build.0 = Release|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Release|x86.ActiveCfg = Release|Any CPU + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96}.Release|x86.Build.0 = Release|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Debug|x64.ActiveCfg = Debug|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Debug|x64.Build.0 = Debug|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Debug|x86.ActiveCfg = Debug|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Debug|x86.Build.0 = Debug|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Release|Any CPU.Build.0 = Release|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Release|x64.ActiveCfg = Release|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Release|x64.Build.0 = Release|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Release|x86.ActiveCfg = Release|Any CPU + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72}.Release|x86.Build.0 = Release|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Debug|x64.ActiveCfg = Debug|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Debug|x64.Build.0 = Debug|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Debug|x86.ActiveCfg = Debug|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Debug|x86.Build.0 = Debug|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Release|Any CPU.Build.0 = Release|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Release|x64.ActiveCfg = Release|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Release|x64.Build.0 = Release|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Release|x86.ActiveCfg = Release|Any CPU + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D}.Release|x86.Build.0 = Release|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Debug|x64.ActiveCfg = Debug|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Debug|x64.Build.0 = Debug|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Debug|x86.ActiveCfg = Debug|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Debug|x86.Build.0 = Debug|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Release|Any CPU.Build.0 = Release|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Release|x64.ActiveCfg = Release|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Release|x64.Build.0 = Release|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Release|x86.ActiveCfg = Release|Any CPU + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6}.Release|x86.Build.0 = Release|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Debug|x64.ActiveCfg = Debug|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Debug|x64.Build.0 = Debug|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Debug|x86.ActiveCfg = Debug|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Debug|x86.Build.0 = Debug|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Release|Any CPU.Build.0 = Release|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Release|x64.ActiveCfg = Release|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Release|x64.Build.0 = Release|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Release|x86.ActiveCfg = Release|Any CPU + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6}.Release|x86.Build.0 = Release|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Debug|x64.ActiveCfg = Debug|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Debug|x64.Build.0 = Debug|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Debug|x86.ActiveCfg = Debug|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Debug|x86.Build.0 = Debug|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Release|Any CPU.Build.0 = Release|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Release|x64.ActiveCfg = Release|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Release|x64.Build.0 = Release|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Release|x86.ActiveCfg = Release|Any CPU + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94}.Release|x86.Build.0 = Release|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Debug|x64.ActiveCfg = Debug|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Debug|x64.Build.0 = Debug|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Debug|x86.ActiveCfg = Debug|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Debug|x86.Build.0 = Debug|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Release|Any CPU.Build.0 = Release|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Release|x64.ActiveCfg = Release|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Release|x64.Build.0 = Release|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Release|x86.ActiveCfg = Release|Any CPU + {2220A59B-5BA3-40E1-A03C-52EA800FDB60}.Release|x86.Build.0 = Release|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Debug|x64.ActiveCfg = Debug|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Debug|x64.Build.0 = Debug|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Debug|x86.ActiveCfg = Debug|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Debug|x86.Build.0 = Debug|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Release|Any CPU.Build.0 = Release|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Release|x64.ActiveCfg = Release|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Release|x64.Build.0 = Release|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Release|x86.ActiveCfg = Release|Any CPU + {49AA662D-563F-4810-880A-5F5BF7949CC6}.Release|x86.Build.0 = Release|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Debug|x64.ActiveCfg = Debug|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Debug|x64.Build.0 = Debug|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Debug|x86.ActiveCfg = Debug|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Debug|x86.Build.0 = Debug|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Release|Any CPU.Build.0 = Release|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Release|x64.ActiveCfg = Release|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Release|x64.Build.0 = Release|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Release|x86.ActiveCfg = Release|Any CPU + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution + {7B2671B3-E9C5-41AD-BB0C-692238558197} = {3C316ABB-08D5-4450-9A4E-91059DB54254} + {7FEA2A01-1660-4D18-B05D-83D356FD7828} = {3C316ABB-08D5-4450-9A4E-91059DB54254} + {9FF9D5FA-1D0C-4743-87E3-CC8C08694CAC} = {3C316ABB-08D5-4450-9A4E-91059DB54254} + {D43E63EA-2210-471E-BFED-D1D33D196554} = {3C316ABB-08D5-4450-9A4E-91059DB54254} + {7A49A922-127C-4786-84B7-53E64D816336} = {3C316ABB-08D5-4450-9A4E-91059DB54254} + {4DEA94AF-D592-4187-8850-A569C93256C9} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {8DB5300A-B38A-4F6D-8FF7-A722DA47667E} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {6050F6A9-F136-4B7B-82D2-57E689463ACA} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {3BB42EB9-A0A3-4E3F-9053-785F429714AE} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {4D5E4789-8437-4F3B-883E-28BBF8A4848F} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {53B1231B-37F5-44BA-80D5-DBA979775F5C} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} {64570222-A5AC-49EE-BEBC-25D61B989A20} = {19C1EE2F-0F4C-4BF6-B677-E0EC37AB3C72} {D78A725D-C3AE-420B-ABA8-255A000D7324} = {64570222-A5AC-49EE-BEBC-25D61B989A20} {459EF701-AB73-40ED-81E6-144D3587C667} = {D78A725D-C3AE-420B-ABA8-255A000D7324} @@ -1172,23 +1388,15 @@ Global {240E1B2A-08A3-439D-B8B2-4D9C18B4AF8A} = {863E6DFF-B0F3-4CFA-8544-260346A7735A} {279D354F-C362-4302-A265-A46FDB070565} = {64570222-A5AC-49EE-BEBC-25D61B989A20} {F1DB0FEA-AF12-4F0E-9277-ADB024560937} = {64570222-A5AC-49EE-BEBC-25D61B989A20} - {7B2671B3-E9C5-41AD-BB0C-692238558197} = {3C316ABB-08D5-4450-9A4E-91059DB54254} - {7FEA2A01-1660-4D18-B05D-83D356FD7828} = {3C316ABB-08D5-4450-9A4E-91059DB54254} - {9FF9D5FA-1D0C-4743-87E3-CC8C08694CAC} = {3C316ABB-08D5-4450-9A4E-91059DB54254} - {D43E63EA-2210-471E-BFED-D1D33D196554} = {3C316ABB-08D5-4450-9A4E-91059DB54254} - {7A49A922-127C-4786-84B7-53E64D816336} = {3C316ABB-08D5-4450-9A4E-91059DB54254} - {4DEA94AF-D592-4187-8850-A569C93256C9} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} - {8DB5300A-B38A-4F6D-8FF7-A722DA47667E} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} - {6050F6A9-F136-4B7B-82D2-57E689463ACA} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} - {3BB42EB9-A0A3-4E3F-9053-785F429714AE} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} - {4D5E4789-8437-4F3B-883E-28BBF8A4848F} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} - {53B1231B-37F5-44BA-80D5-DBA979775F5C} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} {3F057926-562F-4EF4-BFC0-EE62372D4551} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} {3680DAFB-10BA-4A0F-AE40-620D06DAF617} = {3F057926-562F-4EF4-BFC0-EE62372D4551} {6BD85BA8-B3C4-4D79-8858-F6D7676FF2CC} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {613C74E8-720C-4205-8BA7-85B23D2E7881} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {8B06B1D2-80B9-490C-9A36-C7748F58B705} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} {F72DCA2D-0349-42F9-9614-92A38D4B1EA4} = {8B06B1D2-80B9-490C-9A36-C7748F58B705} + {E2D3C4B5-A6F7-4C8D-9E0F-A1B2C3D4E5F9} = {8B06B1D2-80B9-490C-9A36-C7748F58B705} + {C2B3A4D5-E6F7-4A8B-9C0D-E1F2A3B4C5D7} = {8B06B1D2-80B9-490C-9A36-C7748F58B705} + {D2C3B4A5-F6E7-4B8C-9D0E-F1A2B3C4D5E8} = {8B06B1D2-80B9-490C-9A36-C7748F58B705} {8CF6FEA4-624C-4EC9-93D6-EB7626059D7C} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {EADCD78B-04D5-4FE3-855C-E3015531EC8E} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} @@ -1224,8 +1432,22 @@ Global {97F5171D-DF9B-4C2B-B791-1F75A364ED05} = {3F057926-562F-4EF4-BFC0-EE62372D4551} {1452D457-8C24-4BB5-A45E-794F3240212D} = {3F057926-562F-4EF4-BFC0-EE62372D4551} {319846E2-F97B-4547-9134-59B5D7BB9E2D} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {FD068F9A-5220-4E4C-9A0E-EE774EFA391D} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {E00D4FDD-9BDF-4490-8500-8CE0173CC239} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {8FE084F4-BD5D-4088-8440-4A9881D4417D} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {7E9AB5F2-435B-4E1D-A3F5-2AA2D0681AC0} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {F4A221A4-C0EB-4CBC-AF94-9A170B4BF039} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {D3F1A6B8-2C4E-4A9D-B7F0-5E8C1A2B3C4D} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {A1B2C3D4-E5F6-4A7B-8C9D-E1F2A3B4C5D6} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {F1E2D3C4-B5A6-4978-8A9B-C1D2E3F4A5B6} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {A9D4C7E2-6B31-4F58-8E27-3C0D5A1B7F94} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {2220A59B-5BA3-40E1-A03C-52EA800FDB60} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {49AA662D-563F-4810-880A-5F5BF7949CC6} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {E53827E9-FDE3-4301-9F7A-4D4937FFB7B7} = {3F057926-562F-4EF4-BFC0-EE62372D4551} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} EndGlobalSection -EndGlobal \ No newline at end of file +EndGlobal diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryPathTemplatePartDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryPathTemplatePartDtoFixture.cs new file mode 100644 index 00000000..f75ea297 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryPathTemplatePartDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartDtoFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathTemplatePartDto Create( + string? kind = null, + string? representation = null, + bool isOptional = false) + { + return new LibraryPathTemplatePartDto( + kind ?? "Artist", + representation ?? "{0}", + isOptional); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/PermissionEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/PermissionEntityFixture.cs index 5bdb4867..c9793751 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/PermissionEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/PermissionEntityFixture.cs @@ -21,16 +21,22 @@ public class PermissionEntityFixture /// /// Optional. The permission Id. /// Optional. The permission name. + /// Optional. The Id of the user that created the permission. + /// Optional. The time and date when the permission was created. /// The created . - public PermissionEntity Create(Guid? id = null, AuthorizationPermission? permissionName = null) + public PermissionEntity Create( + Guid? id = null, + AuthorizationPermission? permissionName = null, + Guid? createdBy = null, + DateTime? createdOnUtc = null) { return new Faker() .RuleFor(x => x.Id, f => id ?? f.Random.Guid()) .RuleFor(x => x.PermissionName, f => permissionName ?? f.PickRandom()) .RuleFor(x => x.RolePermissions, []) .RuleFor(x => x.UserPermissions, []) - .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) - .RuleFor(x => x.CreatedBy, f => f.Random.Guid()) + .RuleFor(x => x.CreatedOnUtc, f => createdOnUtc ?? f.Date.Past()) + .RuleFor(x => x.CreatedBy, f => createdBy ?? f.Random.Guid()) .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) .RuleFor(x => x.UpdatedBy, f => f.Random.Guid()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs index 7029f0fd..61ae5be5 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,7 +15,9 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; [ExcludeFromCodeCoverage] public class RolePermissionEntityFixture { - private readonly Faker _faker = new(); + // RoleEntityFixture composes this fixture, so the role fixture is resolved lazily to avoid an eager mutual composition cycle. + private readonly Lazy _roleEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); /// /// Creates a random valid . @@ -26,33 +27,20 @@ public class RolePermissionEntityFixture /// Optional. The role the permission is granted to. /// Optional. The Id of the permission granted to the role. /// Optional. The permission granted to the role. + /// Optional. The time and date when the association was created. + /// Optional. The Id of the user that created the association. /// The created . public RolePermissionEntity Create( Guid? id = null, Guid? roleId = null, RoleEntity? role = null, Guid? permissionId = null, - PermissionEntity? permission = null) + PermissionEntity? permission = null, + DateTime? createdOnUtc = null, + Guid? createdBy = null) { - RoleEntity resolvedRole = role ?? new RoleEntity - { - Id = roleId ?? _faker.Random.Guid(), - RoleName = _faker.Random.String2(10), - CreatedOnUtc = _faker.Date.Past(), - CreatedBy = _faker.Random.Guid(), - UpdatedOnUtc = _faker.Date.Recent(), - UpdatedBy = _faker.Random.Guid() - }; - - PermissionEntity resolvedPermission = permission ?? new PermissionEntity - { - Id = permissionId ?? _faker.Random.Guid(), - PermissionName = _faker.PickRandom(), - CreatedOnUtc = _faker.Date.Past(), - CreatedBy = _faker.Random.Guid(), - UpdatedOnUtc = _faker.Date.Recent(), - UpdatedBy = _faker.Random.Guid() - }; + RoleEntity resolvedRole = role ?? _roleEntityFixture.Value.Create(id: roleId); + PermissionEntity resolvedPermission = permission ?? _permissionEntityFixture.Create(id: permissionId); return new Faker() .CustomInstantiator(f => new RolePermissionEntity @@ -62,8 +50,8 @@ public class RolePermissionEntityFixture Role = role ?? resolvedRole, PermissionId = resolvedPermission.Id, Permission = permission ?? resolvedPermission, - CreatedOnUtc = f.Date.Past(), - CreatedBy = f.Random.Guid(), + CreatedOnUtc = createdOnUtc ?? f.Date.Past(), + CreatedBy = createdBy ?? f.Random.Guid(), UpdatedOnUtc = f.Date.Recent(), UpdatedBy = f.Random.Guid() }) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserPermissionEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserPermissionEntityFixture.cs index f94d9984..1e8fe3cb 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserPermissionEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserPermissionEntityFixture.cs @@ -2,6 +2,7 @@ using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -18,8 +19,14 @@ public class UserPermissionEntityFixture /// /// The user the permission is granted to. /// The permission granted to the user. + /// Optional. The time and date when the association was created. + /// Optional. The Id of the user that created the association. /// The created . - public UserPermissionEntity Create(UserEntity user, PermissionEntity permission) + public UserPermissionEntity Create( + UserEntity user, + PermissionEntity permission, + DateTime? createdOnUtc = null, + Guid? createdBy = null) { return new Faker() .CustomInstantiator(f => new UserPermissionEntity @@ -29,8 +36,8 @@ public class UserPermissionEntityFixture User = user, PermissionId = permission.Id, Permission = permission, - CreatedOnUtc = f.Date.Past(), - CreatedBy = user.Id, + CreatedOnUtc = createdOnUtc ?? f.Date.Past(), + CreatedBy = createdBy ?? user.Id, UpdatedOnUtc = f.Random.Bool() ? f.Date.Recent() : null, UpdatedBy = f.Random.Bool() ? user.Id : null }) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs index acce952c..b56ed6da 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs @@ -2,6 +2,7 @@ using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,7 +17,8 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; [ExcludeFromCodeCoverage] public class UserRoleEntityFixture { - private readonly Faker _faker = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); /// /// Creates a random valid . @@ -26,44 +28,33 @@ public class UserRoleEntityFixture /// Optional. The user the role is granted to. /// Optional. The Id of the role granted to the user. /// Optional. The role granted to the user. + /// Whether the user should be included, or forced to . + /// Optional. The time and date when the association was created. + /// Optional. The Id of the user that created the association. /// The created . public UserRoleEntity Create( Guid? id = null, Guid? userId = null, UserEntity? user = null, Guid? roleId = null, - RoleEntity? role = null) + RoleEntity? role = null, + bool includeUser = true, + DateTime? createdOnUtc = null, + Guid? createdBy = null) { - UserEntity resolvedUser = user ?? new UserEntity - { - Id = userId ?? _faker.Random.Guid(), - Username = _faker.Internet.UserName(), - Password = _faker.Internet.Password(), - Libraries = [], - UserRole = null, - UserPermissions = [], - CreatedOnUtc = _faker.Date.Past(), - CreatedBy = _faker.Random.Guid() - }; - - RoleEntity resolvedRole = role ?? new RoleEntity - { - Id = roleId ?? _faker.Random.Guid(), - RoleName = _faker.Random.String2(_faker.Random.Number(1, 50)), - CreatedOnUtc = _faker.Date.Past(), - CreatedBy = _faker.Random.Guid() - }; + UserEntity resolvedUser = user ?? _userEntityFixture.Create(id: userId); + RoleEntity resolvedRole = role ?? _roleEntityFixture.Create(id: roleId); return new Faker() .CustomInstantiator(f => new UserRoleEntity { Id = id ?? f.Random.Guid(), UserId = resolvedUser.Id, - User = user ?? resolvedUser, + User = includeUser ? (user ?? resolvedUser) : null!, RoleId = resolvedRole.Id, Role = role ?? resolvedRole, - CreatedOnUtc = f.Date.Past(), - CreatedBy = f.Random.Guid() + CreatedOnUtc = createdOnUtc ?? f.Date.Past(), + CreatedBy = createdBy ?? f.Random.Guid() }) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumCatalogNumberEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumCatalogNumberEntityFixture.cs new file mode 100644 index 00000000..f6bf044f --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumCatalogNumberEntityFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AlbumCatalogNumberEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The catalog number assigned by the label. + /// The created . + public AlbumCatalogNumberEntity Create( + string? catalogNumber = null) + { + return new AlbumCatalogNumberEntity(catalogNumber ?? _faker.Random.String2(_faker.Random.Number(1, 50))); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs index e7c7b23b..511211c7 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs @@ -6,6 +6,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.Setup; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -24,6 +25,8 @@ public class AlbumEntityFixture private readonly TrackEntityFixture _trackEntityFixture = new(); private readonly TagEntityFixture _tagEntityFixture = new(); private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly AlbumReleaseTypeEntityFixture _albumReleaseTypeEntityFixture = new(); + private readonly AlbumCatalogNumberEntityFixture _albumCatalogNumberEntityFixture = new(); private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new(); private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); @@ -71,10 +74,11 @@ public class AlbumEntityFixture /// Whether the release status should be included, or forced to . /// Whether the total number of discs should be included, or forced to . /// Whether the media format should be included, or forced to . - /// Whether the catalog number should be included, or forced to . + /// Whether the catalog number should be included, or forced to . /// Whether the MusicBrainz release identifier should be included, or forced to . /// Whether the MusicBrainz release group identifier should be included, or forced to . /// Whether the MusicBrainz release artist identifier should be included, or forced to . + /// Optional. The metadata enrichment status of the album. /// The created . public AlbumEntity Create( Guid? id = null, @@ -99,7 +103,7 @@ public class AlbumEntityFixture MusicReleaseStatus? releaseStatus = null, int? totalDiscs = null, MusicMediaFormat? mediaFormat = null, - string? catalogNumber = null, + List? catalogNumbers = null, Guid? musicBrainzReleaseId = null, Guid? musicBrainzReleaseGroupId = null, Guid? musicBrainzReleaseArtistId = null, @@ -118,10 +122,11 @@ public class AlbumEntityFixture bool includeReleaseStatus = true, bool includeTotalDiscs = true, bool includeMediaFormat = true, - bool includeCatalogNumber = true, + bool includeCatalogNumbers = true, bool includeMusicBrainzReleaseId = true, bool includeMusicBrainzReleaseGroupId = true, - bool includeMusicBrainzReleaseArtistId = true) + bool includeMusicBrainzReleaseArtistId = true, + MetadataStatus? metadataStatus = null) { Guid resolvedId = id ?? Guid.NewGuid(); Guid resolvedArtistId = artistId ?? Guid.NewGuid(); @@ -140,6 +145,7 @@ public class AlbumEntityFixture Id = resolvedId, ArtistId = resolvedArtistId, LibraryId = resolvedLibraryId, + MetadataStatus = metadataStatus ?? MetadataStatus.Pending, Title = default!, CreatedOnUtc = default, CreatedBy = default, @@ -147,6 +153,7 @@ public class AlbumEntityFixture }) .RuleFor(x => x.Title, f => title ?? f.Random.String2(f.Random.Number(1, 255))) .RuleFor(x => x.OriginalTitle, f => includeOriginalTitle ? (originalTitle ?? f.Random.String2(f.Random.Number(1, 255))) : null) + .RuleFor(x => x.ReleaseTitle, f => f.Random.String2(f.Random.Number(1, 255))) .RuleFor(x => x.Description, f => includeDescription ? (description ?? f.Random.String2(f.Random.Number(1, 2000))) : null) .RuleFor(x => x.OriginalReleaseDate, includeOriginalReleaseDate ? resolvedOriginalReleaseDate : (DateOnly?)null) .RuleFor(x => x.OriginalReleaseYear, includeOriginalReleaseYear ? resolvedOriginalReleaseYear : (int?)null) @@ -160,13 +167,13 @@ public class AlbumEntityFixture .RuleFor(x => x.OriginalLanguageCode, f => includeOriginalLanguage ? (originalLanguageCode ?? f.Random.String2(2)) : null) .RuleFor(x => x.OriginalLanguageName, f => includeOriginalLanguage ? (originalLanguageName ?? f.Random.String2(f.Random.Number(1, 50))) : null) .RuleFor(x => x.OriginalLanguageNativeName, f => includeOriginalLanguage ? (originalLanguageNativeName ?? f.Random.String2(f.Random.Number(1, 50))) : null) - .RuleFor(x => x.ReleaseType, f => includeReleaseType ? (releaseType ?? f.PickRandom()) : (MusicReleaseType?)null) + .RuleFor(x => x.ReleaseTypes, f => includeReleaseType ? [_albumReleaseTypeEntityFixture.Create(releaseType: releaseType)] : []) .RuleFor(x => x.ReleaseStatus, f => includeReleaseStatus ? (releaseStatus ?? f.PickRandom()) : (MusicReleaseStatus?)null) .RuleFor(x => x.TotalDiscs, includeTotalDiscs ? (totalDiscs ?? Random.Shared.Next(1, 3)) : (int?)null) .RuleFor(x => x.TotalTracks, resolvedTracks.Count) .RuleFor(x => x.MediaFormat, f => includeMediaFormat ? (mediaFormat ?? f.PickRandom()) : (MusicMediaFormat?)null) .RuleFor(x => x.Barcode, f => includeBarcode ? (barcode ?? f.Random.String2(f.Random.Number(12, 13), "0123456789")) : null) - .RuleFor(x => x.CatalogNumber, f => includeCatalogNumber ? (catalogNumber ?? f.Random.String2(f.Random.Number(1, 50))) : null) + .RuleFor(x => x.CatalogNumbers, f => includeCatalogNumbers ? [.. (catalogNumbers ?? [f.Random.String2(f.Random.Number(1, 50))]).Select(catalogNumber => _albumCatalogNumberEntityFixture.Create(catalogNumber: catalogNumber))] : []) .RuleFor(x => x.MusicBrainzReleaseId, f => includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? f.Random.Guid()) : (Guid?)null) .RuleFor(x => x.MusicBrainzReleaseGroupId, f => includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? f.Random.Guid()) : (Guid?)null) .RuleFor(x => x.MusicBrainzReleaseArtistId, f => includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? f.Random.Guid()) : (Guid?)null) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumReleaseTypeEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumReleaseTypeEntityFixture.cs new file mode 100644 index 00000000..38412d90 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumReleaseTypeEntityFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AlbumReleaseTypeEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The type of the release. + /// The created . + public AlbumReleaseTypeEntity Create( + MusicReleaseType? releaseType = null) + { + return new AlbumReleaseTypeEntity(releaseType ?? _faker.PickRandom()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistAliasEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistAliasEntityFixture.cs new file mode 100644 index 00000000..f891e2ea --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistAliasEntityFixture.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtistAliasEntityFixture +{ + private const int MINIMUM_ALIAS_YEAR = 1900; + private const int MAXIMUM_ALIAS_YEAR = 2026; + + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the alias. + /// Optional. The sort name of the alias. + /// Optional. The type of the alias. + /// Optional. The locale the alias is used in. + /// Optional. Whether this is the primary alias of the artist. + /// Optional. The date the alias began being used. + /// Optional. The date the alias stopped being used. + /// Optional. Whether the alias is no longer used. + /// Whether the sort name should be included, or forced to . + /// Whether the type should be included, or forced to . + /// Whether the locale should be included, or forced to . + /// Whether the begin date should be included, or forced to . + /// Whether the end date should be included, or forced to . + /// The created . + public ArtistAliasEntity Create( + string? name = null, + string? sortName = null, + string? type = null, + string? locale = null, + bool? isPrimary = null, + DateOnly? beginDate = null, + DateOnly? endDate = null, + bool? isEnded = null, + bool includeSortName = true, + bool includeType = true, + bool includeLocale = true, + bool includeBeginDate = true, + bool includeEndDate = true) + { + int beginYear = Random.Shared.Next(MINIMUM_ALIAS_YEAR, MAXIMUM_ALIAS_YEAR); + int endYear = Random.Shared.Next(beginYear, Math.Max(beginYear + 1, MAXIMUM_ALIAS_YEAR)); + + return new ArtistAliasEntity( + name ?? _faker.Name.FullName(), + includeSortName ? (sortName ?? _faker.Name.FullName()) : null, + includeType ? (type ?? _faker.Random.ArrayElement(["Artist name", "Search hint"])) : null, + includeLocale ? (locale ?? _faker.Random.String2(2)) : null, + isPrimary ?? _faker.Random.Bool(), + includeBeginDate ? (beginDate ?? new DateOnly(beginYear, 1, 1)) : null, + includeEndDate ? (endDate ?? new DateOnly(endYear, 1, 1)) : null, + isEnded ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIpiEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIpiEntityFixture.cs new file mode 100644 index 00000000..20bfb519 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIpiEntityFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtistIpiEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The value of the IPI code. + /// The created . + public ArtistIpiEntity Create( + string? value = null) + { + return new ArtistIpiEntity(value ?? _faker.Random.String2(_faker.Random.Number(1, 20), "0123456789")); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIsniEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIsniEntityFixture.cs new file mode 100644 index 00000000..7cbf2fcb --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistIsniEntityFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtistIsniEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The value of the ISNI code. + /// The created . + public ArtistIsniEntity Create( + string? value = null) + { + return new ArtistIsniEntity(value ?? _faker.Random.String2(_faker.Random.Number(1, 20), "0123456789X")); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaEntityFixture.cs new file mode 100644 index 00000000..8389106e --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaEntityFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MusicAreaEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The MusicBrainz identifier of the area. + /// Optional. The name of the area. + /// Optional. The sort name of the area. + /// Optional. The disambiguation comment of the area. + /// Optional. The MusicBrainz type of the area. + /// Optional. The ISO 3166 code of the area. + /// Whether the sort name should be included, or forced to . + /// Whether the disambiguation should be included, or forced to . + /// Whether the type should be included, or forced to . + /// Whether the ISO 3166 code should be included, or forced to . + /// The created . + public MusicAreaEntity Create( + Guid? musicBrainzAreaId = null, + string? name = null, + string? sortName = null, + string? disambiguation = null, + string? type = null, + string? iso3166Code = null, + bool includeSortName = true, + bool includeDisambiguation = true, + bool includeType = true, + bool includeIso3166Code = true) + { + return new MusicAreaEntity( + musicBrainzAreaId ?? _faker.Random.Guid(), + name ?? _faker.Address.Country(), + includeSortName ? (sortName ?? _faker.Address.Country()) : null, + includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null, + includeType ? (type ?? _faker.Random.ArrayElement(["Country", "City", "Area"])) : null, + includeIso3166Code ? (iso3166Code ?? _faker.Address.CountryCode()) : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs new file mode 100644 index 00000000..753064fa --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the artwork. + /// Optional. The type of the music library item that owns the artwork. + /// Optional. The Id of the music library item that owns the artwork. + /// Optional. The type of the artwork. + /// Optional. The ordinal of the artwork within its type. + /// Optional. The relative file name of the stored artwork. + /// Optional. The content hash of the stored artwork. + /// Optional. The status of the artwork enrichment. + /// Optional. The name of the plugin that resolved the artwork. + /// Optional. The date and time when the artwork was last resolved. + /// Whether the file name should be included, or forced to . + /// Whether the provider should be included, or forced to . + /// Whether the last update date should be included, or forced to . + /// The created . + public MusicArtworkEntity Create( + Guid? id = null, + MusicArtworkOwnerType? ownerType = null, + Guid? ownerId = null, + ArtworkType? artworkType = null, + int? ordinal = null, + string? fileName = null, + ulong? contentHash = null, + ArtworkStatus? status = null, + string? provider = null, + DateTime? lastUpdateUtc = null, + bool includeFileName = true, + bool includeProvider = true, + bool includeLastUpdateUtc = true) + { + return new MusicArtworkEntity + { + Id = id ?? Guid.NewGuid(), + OwnerType = ownerType ?? _faker.PickRandom(), + OwnerId = ownerId ?? Guid.NewGuid(), + ArtworkType = artworkType ?? _faker.PickRandom(), + Ordinal = ordinal ?? _faker.Random.Int(0, 5), + FileName = includeFileName ? (fileName ?? _faker.System.FilePath()) : null, + ContentHash = contentHash ?? (ulong)_faker.Random.ULong(), + Status = status ?? _faker.PickRandom(), + Provider = includeProvider ? (provider ?? _faker.Company.CompanyName()) : null, + LastUpdateUtc = includeLastUpdateUtc ? (lastUpdateUtc ?? _faker.Date.Recent()) : null, + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = Guid.NewGuid(), + UpdatedOnUtc = null, + UpdatedBy = null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntityFixture.cs new file mode 100644 index 00000000..f5baffc3 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicLibraryScanItemMetadataEntityFixture.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryScanItemMetadataEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the staged metadata. + /// Optional. The Id of the media library scan the staged metadata belongs to. + /// Optional. The Id of the media library the staged metadata belongs to. + /// Optional. The file system path of the music file. + /// Optional. The name of the artist. + /// Optional. The name of the release. + /// Optional. The title of the track. + /// Optional. The number of the track on its disc. + /// Optional. The number of the disc the track belongs to. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The MusicBrainz identifier of the release artist. + /// Optional. The MusicBrainz identifier of the release group. + /// Optional. The MusicBrainz identifier of the release. + /// Optional. The MusicBrainz identifier of the recording. + /// Optional. The MusicBrainz identifier of the track. + /// Optional. The MusicBrainz identifier of the work. + /// Optional. The title of the work. + /// Whether the MusicBrainz identifiers and the work title should be included, or forced to . + /// The created . + public MusicLibraryScanItemMetadataEntity Create( + Guid? id = null, + Guid? libraryScanId = null, + Guid? libraryId = null, + string? path = null, + string? artistName = null, + string? releaseName = null, + string? trackTitle = null, + int? trackNumber = null, + int? discNumber = null, + Guid? musicBrainzArtistId = null, + Guid? musicBrainzReleaseArtistId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzRecordingId = null, + Guid? musicBrainzTrackId = null, + Guid? musicBrainzWorkId = null, + string? workTitle = null, + bool includeMusicBrainzTags = true) + { + return new MusicLibraryScanItemMetadataEntity + { + Id = id ?? Guid.NewGuid(), + LibraryScanId = libraryScanId ?? Guid.NewGuid(), + LibraryId = libraryId ?? Guid.NewGuid(), + Path = path ?? _faker.System.FilePath(), + ArtistName = artistName ?? _faker.Name.FullName(), + ReleaseType = _faker.PickRandom(), + ReleaseYear = Random.Shared.Next(1900, 2026), + ReleaseName = releaseName ?? _faker.Music.Genre(), + TrackTitle = trackTitle ?? _faker.Music.Genre(), + TrackNumber = trackNumber ?? _faker.Random.Int(1, 20), + DiscNumber = discNumber ?? _faker.Random.Int(1, 3), + DurationInSeconds = Random.Shared.Next(60, 7200), + SampleRate = _faker.PickRandom(44100, 48000, 96000), + Channels = _faker.PickRandom(1, 2, 6), + BitDepth = Random.Shared.Next(8, 32), + AudioCodec = _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC"), + Bitrate = Random.Shared.Next(96, 1411), + MusicBrainzArtistId = includeMusicBrainzTags ? musicBrainzArtistId ?? Guid.NewGuid() : null, + MusicBrainzReleaseArtistId = includeMusicBrainzTags ? musicBrainzReleaseArtistId ?? Guid.NewGuid() : null, + MusicBrainzReleaseGroupId = includeMusicBrainzTags ? musicBrainzReleaseGroupId ?? Guid.NewGuid() : null, + MusicBrainzReleaseId = includeMusicBrainzTags ? musicBrainzReleaseId ?? Guid.NewGuid() : null, + MusicBrainzRecordingId = includeMusicBrainzTags ? musicBrainzRecordingId ?? Guid.NewGuid() : null, + MusicBrainzTrackId = includeMusicBrainzTags ? musicBrainzTrackId ?? Guid.NewGuid() : null, + MusicBrainzWorkId = includeMusicBrainzTags ? musicBrainzWorkId ?? Guid.NewGuid() : null, + WorkTitle = includeMusicBrainzTags ? workTitle ?? _faker.Music.Genre() : null + }; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs index 3b039dc2..2fda1e88 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs @@ -6,6 +6,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.Setup; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -46,6 +47,7 @@ public class TrackEntityFixture /// Whether the original release year should be included, or forced to . /// Whether the re-release date should be included, or forced to . /// Whether the re-release year should be included, or forced to . + /// Optional. The metadata enrichment status of the track. /// The created . public TrackEntity Create( Guid? id = null, @@ -62,7 +64,8 @@ public class TrackEntityFixture bool includeOriginalReleaseDate = true, bool includeOriginalReleaseYear = true, bool includeReReleaseDate = true, - bool includeReReleaseYear = true) + bool includeReReleaseYear = true, + MetadataStatus? metadataStatus = null) { Guid resolvedId = id ?? Guid.NewGuid(); Guid resolvedAlbumId = albumId ?? Guid.NewGuid(); @@ -80,6 +83,7 @@ public class TrackEntityFixture Id = resolvedId, AlbumId = resolvedAlbumId, LibraryId = resolvedLibraryId, + MetadataStatus = metadataStatus ?? MetadataStatus.Pending, Path = default!, Title = default!, CreatedOnUtc = default, @@ -113,7 +117,9 @@ public class TrackEntityFixture .RuleFor(x => x.Script, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(x => x.Key, f => f.PickRandom()) .RuleFor(x => x.Bpm, Random.Shared.Next(40, 240)) - .RuleFor(x => x.Work, f => f.Music.Genre()) + .RuleFor(x => x.IsVideo, f => f.Random.Bool()) + .RuleFor(x => x.WorkTitle, f => f.Music.Genre()) + .RuleFor(x => x.WorkType, f => f.Music.Genre()) .RuleFor(x => x.MusicBrainzRecordingId, f => f.Random.Guid()) .RuleFor(x => x.MusicBrainzTrackId, f => f.Random.Guid()) .RuleFor(x => x.MusicBrainzWorkId, f => f.Random.Guid()) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkIswcEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkIswcEntityFixture.cs new file mode 100644 index 00000000..a69c59d9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkIswcEntityFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TrackWorkIswcEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The value of the ISWC. + /// The created . + public TrackWorkIswcEntity Create( + string? value = null) + { + return new TrackWorkIswcEntity(value ?? $"T{_faker.Random.AlphaNumeric(10)}"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkLanguageEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkLanguageEntityFixture.cs new file mode 100644 index 00000000..607df8e6 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackWorkLanguageEntityFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TrackWorkLanguageEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The ISO 639-1 two-letter language code. + /// Optional. The full name of the language in English. + /// Optional. The native name of the language. + /// Whether the native name should be included, or forced to . + /// The created . + public TrackWorkLanguageEntity Create( + string? languageCode = null, + string? languageName = null, + string? nativeName = null, + bool includeNativeName = true) + { + return new TrackWorkLanguageEntity( + languageCode ?? _faker.PickRandom("en", "fr", "de", "es", "it", "ja", "ko", "zh", "pt", "ru"), + languageName ?? _faker.Lorem.Word(), + includeNativeName ? (nativeName ?? _faker.Lorem.Word()) : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntityFixture.cs index 334925bf..d9e327ec 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntityFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class DirectoryScanFingerprintEntityFixture diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs index 4d7afec4..9eefde82 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs @@ -16,6 +16,9 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Ma [ExcludeFromCodeCoverage] public class LibraryEntityFixture { + private readonly LibraryContentLocationEntityFixture _libraryContentLocationEntityFixture = new(); + private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new(); + /// /// Creates a random valid . /// @@ -32,6 +35,8 @@ public class LibraryEntityFixture /// Whether unchanged directories should be skipped during a scan or not. /// Optional. The fingerprint of the metadata provider configuration of the media library. /// Optional. The fingerprint of the artwork provider configuration of the media library. + /// Optional. The ordered parts of the path template of the media library. + /// Optional. The fingerprint of the path template of the media library. /// The created media library entity. public LibraryEntity Create( Guid? id = null, @@ -46,7 +51,9 @@ public class LibraryEntityFixture bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false, string? metadataProvidersConfigurationFingerprint = null, - string? artworkProvidersConfigurationFingerprint = null) + string? artworkProvidersConfigurationFingerprint = null, + IEnumerable? pathTemplateParts = null, + string? pathTemplateFingerprint = null) { return new Faker() .CustomInstantiator(f => new LibraryEntity @@ -57,6 +64,7 @@ public class LibraryEntityFixture CoverImage = default, LibraryType = default, ContentLocations = [], + PathTemplateParts = [], LibraryScans = [], IsEnabled = isEnabled, IsLocked = isLocked, @@ -65,6 +73,7 @@ public class LibraryEntityFixture ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan, MetadataProvidersConfigurationFingerprint = metadataProvidersConfigurationFingerprint, ArtworkProvidersConfigurationFingerprint = artworkProvidersConfigurationFingerprint, + PathTemplateFingerprint = pathTemplateFingerprint, CreatedOnUtc = default, CreatedBy = default, UpdatedOnUtc = null, @@ -76,8 +85,9 @@ public class LibraryEntityFixture .RuleFor(library => library.ContentLocations, f => { IEnumerable paths = contentLocations ?? [f.System.DirectoryPath(), f.System.DirectoryPath()]; - return [.. paths.Select(path => new LibraryContentLocationEntity() { Path = path })]; + return [.. paths.Select(path => _libraryContentLocationEntityFixture.Create(path: path))]; }) + .RuleFor(library => library.PathTemplateParts, f => pathTemplateParts is null ? [] : [.. pathTemplateParts]) .RuleFor(library => library.CreatedOnUtc, f => f.Date.Past()) .RuleFor(library => library.CreatedBy, f => f.Random.Guid()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntityFixture.cs new file mode 100644 index 00000000..bdc0c908 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntityFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartEntityFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The zero based position of the part in the path template. + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathTemplatePartEntity Create( + int? position = null, + LibraryPathPartKind? kind = null, + string? representation = null, + bool isOptional = false) + { + return new Faker() + .CustomInstantiator(f => new LibraryPathTemplatePartEntity + { + Position = position ?? 0, + Kind = default, + Representation = default!, + IsOptional = isOptional + }) + .RuleFor(part => part.Kind, f => kind ?? f.PickRandom()) + .RuleFor(part => part.Representation, f => representation ?? "{0}") + .Generate(); + } + + /// + /// Creates a list of instances with sequential positions. + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(index => Create(position: index))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntityFixture.cs index 5ce50582..672ea40d 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntityFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryScanResultEntityFixture diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntityFixture.cs index 7ce61553..f2ef4367 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntityFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryScanSnapshotEntityFixture diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntityFixture.cs index c1b8487a..734e2d7e 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntityFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryScanStagingResultsEntityFixture diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs index c8edfd88..2fa6e5b2 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs @@ -1,8 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Fixtures.Common.Setup;using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.Setup; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; using System.Collections.Generic; @@ -19,6 +20,10 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Wr public class BookEntityFixture { private readonly Faker _faker = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly IsbnEntityFixture _isbnEntityFixture = new(); + private readonly BookRatingEntityFixture _bookRatingEntityFixture = new(); /// /// Creates a random valid . @@ -60,8 +65,8 @@ public class BookEntityFixture .RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2)) .RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.Tags, f => includeMetadata ? [.. CreateTags(f.Random.Number(1, 5))] : []) - .RuleFor(x => x.Genres, f => includeMetadata ? [.. CreateGenres(f.Random.Number(1, 5))] : []) + .RuleFor(x => x.Tags, f => includeMetadata ? [.. _tagEntityFixture.CreateMany(f.Random.Number(1, 5))] : []) + .RuleFor(x => x.Genres, f => includeMetadata ? [.. _genreEntityFixture.CreateMany(f.Random.Number(1, 5))] : []) .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) .RuleFor(x => x.PageCount, Random.Shared.Next(100, 300)) .RuleFor(x => x.Format, f => f.PickRandom()) @@ -76,8 +81,8 @@ public class BookEntityFixture .RuleFor(x => x.GoogleBooksId, CreateGoogleBooksId) .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") - .RuleFor(x => x.ISBNs, f => includeMetadata ? CreateIsbns(f.Random.Number(1, 5)) : []) - .RuleFor(x => x.Ratings, f => includeMetadata ? CreateBookRatings(f.Random.Number(1, 5)) : []) + .RuleFor(x => x.ISBNs, f => includeMetadata ? _isbnEntityFixture.CreateMany(f.Random.Number(1, 5)) : []) + .RuleFor(x => x.Ratings, f => includeMetadata ? _bookRatingEntityFixture.CreateMany(f.Random.Number(1, 5)) : []) .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) .Generate(); @@ -93,30 +98,6 @@ public class BookEntityFixture return [.. Enumerable.Range(0, count).Select(_ => Create())]; } - /// - /// Creates a list of tag entities with random data. - /// - /// The number of tags to create. - /// A list of randomly generated tag entities. - private static List CreateTags(int count) - { - return new Faker() - .CustomInstantiator(f => new TagEntity(f.Random.String2(f.Random.Number(1, 50)))) - .Generate(count); - } - - /// - /// Creates a list of genre entities with random data. - /// - /// The number of genres to create. - /// A list of randomly generated genre entities. - private static List CreateGenres(int count) - { - return new Faker() - .CustomInstantiator(f => new GenreEntity(f.Random.String2(f.Random.Number(1, 50)))) - .Generate(count); - } - /// /// Creates a valid Library of Congress Control Number (LCCN). /// @@ -172,73 +153,4 @@ public class BookEntityFixture const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])]); } - - /// - /// Creates a list of ISBN entities with random data. - /// - /// The number of ISBNs to create. - /// A list of randomly generated ISBN entities. - private static List CreateIsbns(int count) - { - return new Faker() - .CustomInstantiator(f => - { - string isbnValue = CreateIsbn(f); - return new IsbnEntity(isbnValue, isbnValue.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10); - }) - .Generate(count); - } - - /// - /// Creates a valid ISBN (International Standard Book Number). - /// - /// The Faker instance used for generating random data. - /// A properly formatted ISBN-10 or ISBN-13 string with valid checksum. - private static string CreateIsbn(Faker f) - { - bool isIsbn13 = f.Random.Bool(); - if (isIsbn13) - { - string prefix = f.Random.Bool() ? "978" : "979"; - string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); - string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); - string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); - string isbn = $"{prefix}{group[..1]}{publisher}{title}"; - int sum = 0; - for (int i = 0; i < 12; i++) - sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); - int checkDigit = (10 - (sum % 10)) % 10; - return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; - } - else - { - int[] digits = new int[9]; - for (int i = 0; i < 9; i++) - digits[i] = f.Random.Number(0, 9); - int sum = 0; - for (int i = 0; i < 9; i++) - sum += (10 - i) * digits[i]; - int checkDigit = (11 - (sum % 11)) % 11; - string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString(); - return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; - } - } - - /// - /// Creates a list of book rating entities with random data. - /// - /// The number of ratings to create. - /// A list of randomly generated book rating entities. - private static List CreateBookRatings(int count) - { - return new Faker() - .CustomInstantiator(f => new BookRatingEntity( - f.Random.Decimal(1, 5), - 5, - f.PickRandom(), - f.Random.Number(1, 1000) - )) - .Generate(count); - } - } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs index 0ad25a7d..729cfa40 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs @@ -18,20 +18,22 @@ public class IsbnEntityFixture private readonly Faker _faker = new(); /// - /// Creates a random valid . + /// Creates a random valid , with a value that satisfies the ISBN checksum and a format that matches it. /// /// Optional. The ISBN value. /// Optional. The format of the ISBN. /// Whether the value should be included, or forced to . + /// Whether the format should be included, or forced to . /// The created . public IsbnEntity Create( - string? value = null, - IsbnFormat? format = null, - bool includeValue = true) + string? value = null, + IsbnFormat? format = null, + bool includeValue = true, + bool includeFormat = true) { - return new IsbnEntity( - includeValue ? value ?? _faker.Random.String2(13, "0123456789") : null, - format); + string? resolvedValue = includeValue ? value ?? CreateValidIsbn13() : null; + IsbnFormat? resolvedFormat = includeFormat ? format ?? InferFormat(resolvedValue) : null; + return new IsbnEntity(resolvedValue, resolvedFormat); } /// @@ -43,4 +45,33 @@ public class IsbnEntityFixture { return [.. Enumerable.Range(0, count).Select(_ => Create())]; } + + /// + /// Infers the format of an ISBN from the number of digits of its value. + /// + /// The ISBN value whose format is inferred. + /// The inferred ISBN format. + private static IsbnFormat InferFormat(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return IsbnFormat.Isbn13; + + int digitCount = value.Count(char.IsLetterOrDigit); + return digitCount is 10 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13; + } + + /// + /// Generates a random ISBN-13 value with a valid check digit. + /// + /// A valid ISBN-13 value of 13 digits. + private string CreateValidIsbn13() + { + string prefix = _faker.Random.Bool() ? "978" : "979"; + string firstTwelveDigits = prefix + _faker.Random.String2(9, "0123456789"); + int sum = 0; + for (int index = 0; index < 12; index++) + sum += index % 2 == 0 ? firstTwelveDigits[index] - '0' : 3 * (firstTwelveDigits[index] - '0'); + int checkDigit = (10 - (sum % 10)) % 10; + return firstTwelveDigits + checkDigit; + } } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs index f6432ad8..6f582f14 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs @@ -32,6 +32,8 @@ public class UserEntityFixture /// Optional collection of libraries to pin for the user, or to generate them based on . /// Whether the user role association should be included, or forced to . /// Whether the user permission associations should be included, or forced to an empty collection. + /// Optional. The Id of the user that created the user. + /// Optional. The time and date when the user was created. /// The created user entity. public UserEntity Create( int libraryCount = 0, @@ -42,7 +44,9 @@ public class UserEntityFixture IEnumerable? userPermissions = null, ICollection? libraries = null, bool includeUserRole = false, - bool includeUserPermissions = false) + bool includeUserPermissions = false, + Guid? createdBy = null, + DateTime? createdOnUtc = null) { Guid userId = id ?? Guid.NewGuid(); ICollection resolvedLibraries = libraries ?? (libraryCount > 0 @@ -60,11 +64,11 @@ public class UserEntityFixture Libraries = resolvedLibraries, UserPermissions = includeUserPermissions ? (userPermissions ?? []).ToList() : [], UserRole = includeUserRole ? userRole : null, - CreatedBy = userId + CreatedBy = createdBy ?? userId }) .RuleFor(x => x.Username, f => username ?? f.Internet.UserName()) .RuleFor(x => x.Password, f => password ?? Uri.EscapeDataString(f.Internet.Password())) - .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) + .RuleFor(x => x.CreatedOnUtc, f => createdOnUtc ?? f.Date.Past()) .RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32) : null) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs index 22d42e9a..73ab2a18 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs @@ -22,17 +22,20 @@ public class MediaSettingsDtoFixture /// Optional. The root directory where media files are stored. /// Optional. The directory where media library files are stored. /// Optional. The directory where the media item files are stored. + /// Optional. The directory where the music library item files are stored. /// The created . public MediaSettingsDto Create( string? rootDirectory = null, string? librariesDirectory = null, - string? booksDirectory = null) + string? booksDirectory = null, + string? musicDirectory = null) { return new MediaSettingsDto { RootDirectory = rootDirectory ?? _faker.System.DirectoryPath(), LibrariesDirectory = librariesDirectory ?? _faker.System.DirectoryPath(), - BooksDirectory = booksDirectory ?? _faker.System.DirectoryPath() + BooksDirectory = booksDirectory ?? _faker.System.DirectoryPath(), + MusicDirectory = musicDirectory ?? _faker.System.DirectoryPath() }; } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs index 22728308..29b8f426 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Application.Fixtures.Common.Utilities; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ValidatorUtilitiesTestRequestFixture diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryFixture.cs index 008ab95b..39dcc017 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryFixture.cs @@ -19,15 +19,16 @@ public class CheckPathExistsQueryFixture /// /// Optional. The file system path. /// Whether to include hidden file system elements or not. + /// Whether the path should be included, or forced to . /// The created query. - public CheckPathExistsQuery Create(string? path = null, bool shouldIncludeHiddenElements = true) + public CheckPathExistsQuery Create(string? path = null, bool shouldIncludeHiddenElements = true, bool includePath = true) { return new Faker() .CustomInstantiator(f => new CheckPathExistsQuery( default!, default )) - .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.Path, f => includePath ? (path ?? f.System.FilePath()) : null) .RuleFor(x => x.ShouldIncludeHiddenElements, shouldIncludeHiddenElements); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryFixture.cs index 6996d6e1..6b35b852 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryFixture.cs @@ -18,13 +18,14 @@ public class ValidatePathQueryFixture /// Creates a random valid query to validate a path. /// /// Optional. The file system path. + /// Whether the path should be included, or forced to . /// The created query. - public ValidatePathQuery Create(string? path = null) + public ValidatePathQuery Create(string? path = null, bool includePath = true) { return new Faker() .CustomInstantiator(f => new ValidatePathQuery( default!)) - .RuleFor(x => x.Path, f => path ?? f.System.FilePath()); + .RuleFor(x => x.Path, f => includePath ? (path ?? f.System.FilePath()) : null); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryFixture.cs index 9d6e2a7d..1cf7c399 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryFixture.cs @@ -19,15 +19,16 @@ public class GetThumbnailQueryFixture /// /// Optional. The file system path. /// Optional. The thumbnail quality. + /// Whether the path should be included, or forced to . /// The created query. - public GetThumbnailQuery Create(string? path = null, int? quality = null) + public GetThumbnailQuery Create(string? path = null, int? quality = null, bool includePath = true) { return new Faker() .CustomInstantiator(f => new GetThumbnailQuery( default!, default )) - .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.Path, f => includePath ? (path ?? f.System.FilePath()) : null) .RuleFor(x => x.Quality, f => quality ?? f.Random.Int()); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandFixture.cs index 773d80c0..66158351 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandFixture.cs @@ -25,7 +25,7 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrar public class AddAlbumCommandFixture { private readonly Faker _faker = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); @@ -37,8 +37,11 @@ public class AddAlbumCommandFixture /// Optional. The Id of the artist the album belongs to, taken from the route. /// Optional. The album metadata of the album. /// Optional. The physical or digital medium of the album. + /// Optional. The outermost physical packaging of the album. /// Optional. The barcode of the album. /// Optional. The catalog number of the album. + /// Optional. The name of the label that issued the album. + /// Optional. The ASIN of the album. /// Optional. The MusicBrainz identifier of the release. /// Optional. The MusicBrainz identifier of the release group. /// Optional. The MusicBrainz identifier of the release artist. @@ -50,8 +53,11 @@ public class AddAlbumCommandFixture /// Whether the artist Id should be included, or forced to . /// Whether the metadata should be included, or forced to . /// Whether the media format should be included, or forced to . + /// Whether the packaging should be included, or forced to . /// Whether the barcode should be included, or forced to . - /// Whether the catalog number should be included, or forced to . + /// Whether the catalog number should be included, or forced to . + /// Whether the label should be included, or forced to . + /// Whether the ASIN should be included, or forced to . /// Whether the MusicBrainz release Id should be included, or forced to . /// Whether the MusicBrainz release group Id should be included, or forced to . /// Whether the MusicBrainz release artist Id should be included, or forced to . @@ -63,10 +69,13 @@ public class AddAlbumCommandFixture public AddAlbumCommand Create( string? libraryId = null, string? artistId = null, - AlbumMetadataDto? metadata = null, + MusicAlbumMetadataDto? metadata = null, MusicMediaFormat? mediaFormat = null, + MusicReleasePackaging? packaging = null, string? barcode = null, - string? catalogNumber = null, + List? catalogNumbers = null, + string? label = null, + string? asin = null, Guid? musicBrainzReleaseId = null, Guid? musicBrainzReleaseGroupId = null, Guid? musicBrainzReleaseArtistId = null, @@ -78,8 +87,11 @@ public class AddAlbumCommandFixture bool includeArtistId = true, bool includeMetadata = true, bool includeMediaFormat = true, + bool includePackaging = true, bool includeBarcode = true, - bool includeCatalogNumber = true, + bool includeCatalogNumbers = true, + bool includeLabel = true, + bool includeAsin = true, bool includeMusicBrainzReleaseId = true, bool includeMusicBrainzReleaseGroupId = true, bool includeMusicBrainzReleaseArtistId = true, @@ -94,10 +106,13 @@ public class AddAlbumCommandFixture return new AddAlbumCommand( resolvedLibraryId, resolvedArtistId, - includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMetadata ? (metadata ?? _musicAlbumMetadataDtoFixture.Create()) : null, includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includePackaging ? (packaging ?? _faker.PickRandom()) : null, includeBarcode ? (barcode ?? _faker.Random.String2(_faker.Random.Int(12, 13), "0123456789")) : null, - includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(_faker.Random.Int(1, 50))) : null, + includeCatalogNumbers ? (catalogNumbers ?? [_faker.Random.AlphaNumeric(_faker.Random.Int(1, 50))]) : null, + includeLabel ? (label ?? _faker.Company.CompanyName()) : null, + includeAsin ? (asin ?? _faker.Random.AlphaNumeric(10)) : null, includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs index 6f158dbc..dfed2b9d 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs @@ -23,7 +23,7 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrar public class UpdateAlbumCommandFixture { private readonly Faker _faker = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); @@ -35,8 +35,11 @@ public class UpdateAlbumCommandFixture /// Optional. The Id of the album to update, taken from the route. /// Optional. The album metadata of the album. /// Optional. The physical or digital medium of the album. + /// Optional. The outermost physical packaging of the album. /// Optional. The barcode of the album. /// Optional. The catalog number of the album. + /// Optional. The name of the label that issued the album. + /// Optional. The ASIN of the album. /// Optional. The MusicBrainz identifier of the release. /// Optional. The MusicBrainz identifier of the release group. /// Optional. The MusicBrainz identifier of the release artist. @@ -47,8 +50,11 @@ public class UpdateAlbumCommandFixture /// Whether the album Id should be included, or forced to . /// Whether the metadata should be included, or forced to . /// Whether the media format should be included, or forced to . + /// Whether the packaging should be included, or forced to . /// Whether the barcode should be included, or forced to . - /// Whether the catalog number should be included, or forced to . + /// Whether the catalog number should be included, or forced to . + /// Whether the label should be included, or forced to . + /// Whether the ASIN should be included, or forced to . /// Whether the MusicBrainz release Id should be included, or forced to . /// Whether the MusicBrainz release group Id should be included, or forced to . /// Whether the MusicBrainz release artist Id should be included, or forced to . @@ -59,10 +65,13 @@ public class UpdateAlbumCommandFixture string? libraryId = null, string? artistId = null, string? albumId = null, - AlbumMetadataDto? metadata = null, + MusicAlbumMetadataDto? metadata = null, MusicMediaFormat? mediaFormat = null, + MusicReleasePackaging? packaging = null, string? barcode = null, - string? catalogNumber = null, + List? catalogNumbers = null, + string? label = null, + string? asin = null, Guid? musicBrainzReleaseId = null, Guid? musicBrainzReleaseGroupId = null, Guid? musicBrainzReleaseArtistId = null, @@ -73,8 +82,11 @@ public class UpdateAlbumCommandFixture bool includeAlbumId = true, bool includeMetadata = true, bool includeMediaFormat = true, + bool includePackaging = true, bool includeBarcode = true, - bool includeCatalogNumber = true, + bool includeCatalogNumbers = true, + bool includeLabel = true, + bool includeAsin = true, bool includeMusicBrainzReleaseId = true, bool includeMusicBrainzReleaseGroupId = true, bool includeMusicBrainzReleaseArtistId = true, @@ -85,10 +97,13 @@ public class UpdateAlbumCommandFixture includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null, - includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMetadata ? (metadata ?? _musicAlbumMetadataDtoFixture.Create()) : null, includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includePackaging ? (packaging ?? _faker.PickRandom()) : null, includeBarcode ? (barcode ?? _faker.Random.String2(_faker.Random.Int(12, 13), "0123456789")) : null, - includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(_faker.Random.Int(1, 50))) : null, + includeCatalogNumbers ? (catalogNumbers ?? [_faker.Random.AlphaNumeric(_faker.Random.Int(1, 50))]) : null, + includeLabel ? (label ?? _faker.Company.CompanyName()) : null, + includeAsin ? (asin ?? _faker.Random.AlphaNumeric(10)) : null, includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs index 39e59696..4a90ad85 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs @@ -4,7 +4,11 @@ using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Comm using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -20,47 +24,64 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrar public class AddArtistCommandFixture { private readonly Faker _faker = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); /// /// Creates a random valid command to add an artist. /// /// Optional. The Id of the media library the artist belongs to, taken from the route. - /// Optional. The name of the artist. + /// Optional. The metadata of the artist. /// Optional. The website of the artist. /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The ISNI codes of the artist. /// Optional. The media contributors that make up the artist. + /// Optional. The ratings of the artist. /// Optional. The albums of the artist, each with its own tracks. /// Whether the library Id should be included, or forced to . - /// Whether the name should be included, or forced to . + /// Whether the metadata should be included, or forced to . /// Whether the website should be included, or forced to . /// Whether the MusicBrainz identifier should be included, or forced to . + /// Whether the IPI codes should be included, or forced to . + /// Whether the ISNI codes should be included, or forced to . /// Whether the contributors should be included, or forced to . + /// Whether the ratings should be included, or forced to . /// Whether the albums should be included, or forced to . /// The created command to add an artist. public AddArtistCommand Create( string? libraryId = null, - string? name = null, + MusicArtistMetadataDto? metadata = null, string? website = null, Guid? musicBrainzArtistId = null, + List? ipis = null, + List? isnis = null, List? contributors = null, + List? ratings = null, List? albums = null, bool includeLibraryId = true, - bool includeName = true, + bool includeMetadata = true, bool includeWebsite = true, bool includeMusicBrainzArtistId = true, + bool includeIpis = true, + bool includeIsnis = true, bool includeContributors = true, + bool includeRatings = true, bool includeAlbums = true) { string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null; return new AddArtistCommand( resolvedLibraryId, - includeName ? (name ?? _faker.Name.FullName()) : null, + includeMetadata ? (metadata ?? _musicArtistMetadataDtoFixture.Create()) : null, includeWebsite ? (website ?? _faker.Internet.Url()) : null, includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeIpis ? (ipis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(9))]) : null, + includeIsnis ? (isnis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(16))]) : null, includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, + includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, includeAlbums ? (albums ?? GenerateAlbums(resolvedLibraryId)) : null); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs index 43137c90..cc87ed9a 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs @@ -4,7 +4,11 @@ using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Comm using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -20,41 +24,55 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrar public class UpdateArtistCommandFixture { private readonly Faker _faker = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); /// /// Creates a random valid command to update an artist. /// /// Optional. The Id of the media library the artist belongs to, taken from the route. /// Optional. The Id of the artist, taken from the route. - /// Optional. The name of the artist. + /// Optional. The metadata of the artist. /// Optional. The website of the artist. /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The ISNI codes of the artist. /// Optional. The media contributors that make up the artist. + /// Optional. The ratings of the artist. /// Optional. The albums of the artist, each with its own tracks. /// Whether the library Id should be included, or forced to . /// Whether the artist Id should be included, or forced to . - /// Whether the name should be included, or forced to . + /// Whether the metadata should be included, or forced to . /// Whether the website should be included, or forced to . /// Whether the MusicBrainz identifier should be included, or forced to . + /// Whether the IPI codes should be included, or forced to . + /// Whether the ISNI codes should be included, or forced to . /// Whether the contributors should be included, or forced to . + /// Whether the ratings should be included, or forced to . /// Whether the albums should be included, or forced to . /// The created command to update an artist. public UpdateArtistCommand Create( string? libraryId = null, string? artistId = null, - string? name = null, + MusicArtistMetadataDto? metadata = null, string? website = null, Guid? musicBrainzArtistId = null, + List? ipis = null, + List? isnis = null, List? contributors = null, + List? ratings = null, List? albums = null, bool includeLibraryId = true, bool includeArtistId = true, - bool includeName = true, + bool includeMetadata = true, bool includeWebsite = true, bool includeMusicBrainzArtistId = true, + bool includeIpis = true, + bool includeIsnis = true, bool includeContributors = true, + bool includeRatings = true, bool includeAlbums = true) { string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null; @@ -62,10 +80,13 @@ public class UpdateArtistCommandFixture return new UpdateArtistCommand( resolvedLibraryId, includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, - includeName ? (name ?? _faker.Name.FullName()) : null, + includeMetadata ? (metadata ?? _musicArtistMetadataDtoFixture.Create()) : null, includeWebsite ? (website ?? _faker.Internet.Url()) : null, includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeIpis ? (ipis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(9))]) : null, + includeIsnis ? (isnis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(16))]) : null, includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, + includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, includeAlbums ? (albums ?? GenerateAlbums(resolvedLibraryId)) : null); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandFixture.cs index 8bee2fae..8d3567e3 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandFixture.cs @@ -26,7 +26,8 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrar public class AddTrackCommandFixture { private readonly Faker _faker = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly MoodDtoFixture _moodDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -45,10 +46,9 @@ public class AddTrackCommandFixture /// Optional. The script used by the language of the track. /// Optional. The musical key of the track. /// Optional. The tempo of the track in beats per minute. - /// Optional. The title of the work the track is a recording of. + /// Optional. The work the track is a recording of. /// Optional. The MusicBrainz identifier of the recording. /// Optional. The MusicBrainz identifier of the track. - /// Optional. The MusicBrainz identifier of the work. /// Optional. The list of moods of the track. /// Optional. The list of ISRC of the track. /// Optional. The list of media contributors that performed on the track. @@ -67,7 +67,6 @@ public class AddTrackCommandFixture /// Whether the work should be included, or forced to . /// Whether the MusicBrainz recording Id should be included, or forced to . /// Whether the MusicBrainz track Id should be included, or forced to . - /// Whether the MusicBrainz work Id should be included, or forced to . /// Whether the moods should be included, or forced to . /// Whether the ISRC codes should be included, or forced to . /// Whether the contributors should be included, or forced to . @@ -78,16 +77,15 @@ public class AddTrackCommandFixture string? artistId = null, string? albumId = null, string? path = null, - AudioMetadataDto? metadata = null, + MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, string? script = null, MusicKey? key = null, int? bpm = null, - string? work = null, + MusicWorkDto? work = null, Guid? musicBrainzRecordingId = null, Guid? musicBrainzTrackId = null, - Guid? musicBrainzWorkId = null, List? moods = null, List? isrcs = null, List? contributors = null, @@ -106,7 +104,6 @@ public class AddTrackCommandFixture bool includeWork = true, bool includeMusicBrainzRecordingId = true, bool includeMusicBrainzTrackId = true, - bool includeMusicBrainzWorkId = true, bool includeMoods = true, bool includeIsrcs = true, bool includeContributors = true, @@ -117,16 +114,15 @@ public class AddTrackCommandFixture includeArtistId ? artistId ?? Guid.NewGuid().ToString() : null, includeAlbumId ? albumId ?? Guid.NewGuid().ToString() : null, includePath ? path ?? Path.Combine(Path.GetTempPath(), "lumina-tracks", _faker.System.FileName()) : null, - includeMetadata ? metadata ?? _audioMetadataDtoFixture.Create() : null, + includeMetadata ? metadata ?? _musicTrackMetadataDtoFixture.Create() : null, includeTrackNumber ? trackNumber ?? _faker.Random.Int(1, 30) : null, includeDiscNumber ? discNumber ?? _faker.Random.Int(1, 3) : null, includeScript ? script ?? _faker.Random.AlphaNumeric(4) : null, includeKey ? key ?? _faker.PickRandom() : null, includeBpm ? bpm ?? _faker.Random.Int(40, 220) : null, - includeWork ? work ?? _faker.Lorem.Sentence() : null, + includeWork ? work ?? _musicWorkDtoFixture.Create() : null, includeMusicBrainzRecordingId ? musicBrainzRecordingId ?? _faker.Random.Guid() : null, includeMusicBrainzTrackId ? musicBrainzTrackId ?? _faker.Random.Guid() : null, - includeMusicBrainzWorkId ? musicBrainzWorkId ?? _faker.Random.Guid() : null, includeMoods ? moods ?? _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null, includeIsrcs ? isrcs ?? _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null, includeContributors ? contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs index 54bcd79b..2638718d 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs @@ -25,7 +25,8 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrar public class UpdateTrackCommandFixture { private readonly Faker _faker = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly MoodDtoFixture _moodDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -45,10 +46,9 @@ public class UpdateTrackCommandFixture /// Optional. The script used by the language of the track. /// Optional. The musical key of the track. /// Optional. The tempo of the track in beats per minute. - /// Optional. The title of the work the track is a recording of. + /// Optional. The work the track is a recording of. /// Optional. The MusicBrainz identifier of the recording. /// Optional. The MusicBrainz identifier of the track. - /// Optional. The MusicBrainz identifier of the work. /// Optional. The moods of the track. /// Optional. The ISRC codes of the track. /// Optional. The media contributors that performed on the track. @@ -60,7 +60,6 @@ public class UpdateTrackCommandFixture /// Whether the work should be included, or forced to . /// Whether the MusicBrainz recording Id should be included, or forced to . /// Whether the MusicBrainz track Id should be included, or forced to . - /// Whether the MusicBrainz work Id should be included, or forced to . /// Whether the moods should be included, or forced to . /// Whether the ISRC codes should be included, or forced to . /// Whether the metadata should be included, or forced to . @@ -79,16 +78,15 @@ public class UpdateTrackCommandFixture string? albumId = null, string? trackId = null, string? path = null, - AudioMetadataDto? metadata = null, + MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, string? script = null, MusicKey? key = null, int? bpm = null, - string? work = null, + MusicWorkDto? work = null, Guid? musicBrainzRecordingId = null, Guid? musicBrainzTrackId = null, - Guid? musicBrainzWorkId = null, List? moods = null, List? isrcs = null, List? contributors = null, @@ -100,7 +98,6 @@ public class UpdateTrackCommandFixture bool includeWork = true, bool includeMusicBrainzRecordingId = true, bool includeMusicBrainzTrackId = true, - bool includeMusicBrainzWorkId = true, bool includeMoods = true, bool includeIsrcs = true, bool includeMetadata = true, @@ -119,16 +116,15 @@ public class UpdateTrackCommandFixture includeAlbumId ? (albumId ?? _faker.Random.Guid().ToString()) : null, includeTrackId ? (trackId ?? _faker.Random.Guid().ToString()) : null, includePath ? (path ?? _faker.System.FilePath()) : null, - includeMetadata ? (metadata ?? _audioMetadataDtoFixture.Create()) : null, + includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null, includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 20)) : null, includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null, includeScript ? (script ?? _faker.Random.String2(_faker.Random.Number(1, 50))) : null, includeKey ? (key ?? _faker.PickRandom()) : null, includeBpm ? (bpm ?? _faker.Random.Int(40, 240)) : null, - includeWork ? (work ?? _faker.Music.Genre()) : null, + includeWork ? (work ?? _musicWorkDtoFixture.Create()) : null, includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null, includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null, - includeMusicBrainzWorkId ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null, includeMoods ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, includeIsrcs ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs index 96e537b3..4d129a24 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Collections.Generic; @@ -27,6 +28,7 @@ public class AddLibraryCommandFixture /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. + /// Optional. The ordered parts of the path template of the media library. /// The created command. public AddLibraryCommand Create( string? title = null, @@ -37,7 +39,8 @@ public class AddLibraryCommandFixture bool isLocked = false, bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, - bool shouldSkipUnchangedDirectoriesDuringScan = false) + bool shouldSkipUnchangedDirectoriesDuringScan = false, + LibraryPathTemplatePartDto[]? pathTemplateParts = null) { return new Faker() .CustomInstantiator(f => new AddLibraryCommand( @@ -49,7 +52,8 @@ public class AddLibraryCommandFixture false, true, true, - false + false, + null )) .RuleFor(x => x.Title, f => title ?? f.Lorem.Word()) .RuleFor(x => x.LibraryType, f => libraryType ?? f.Random.Enum().ToString()) @@ -60,6 +64,7 @@ public class AddLibraryCommandFixture .RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb) .RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories) .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) + .RuleFor(x => x.PathTemplateParts, pathTemplateParts) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs index 284c8d6d..d02b63b6 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; @@ -30,6 +31,7 @@ public class UpdateLibraryCommandFixture /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. + /// Optional. The ordered parts of the path template of the media library. /// The created command. public UpdateLibraryCommand Create( Guid? id = null, @@ -42,7 +44,8 @@ public class UpdateLibraryCommandFixture bool isLocked = false, bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, - bool shouldSkipUnchangedDirectoriesDuringScan = false) + bool shouldSkipUnchangedDirectoriesDuringScan = false, + LibraryPathTemplatePartDto[]? pathTemplateParts = null) { return new Faker() .CustomInstantiator(f => new UpdateLibraryCommand( @@ -56,7 +59,8 @@ public class UpdateLibraryCommandFixture false, true, true, - false + false, + null )) .RuleFor(x => x.Id, id ?? Guid.NewGuid()) .RuleFor(x => x.OwnerId, ownerId ?? Guid.NewGuid()) @@ -69,6 +73,7 @@ public class UpdateLibraryCommandFixture .RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb) .RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories) .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) + .RuleFor(x => x.PathTemplateParts, pathTemplateParts) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryFixture.cs new file mode 100644 index 00000000..79b242d9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available path parts are retrieved. + /// The created . + public GetLibraryPathTemplatePartsQuery Create(string? libraryType = null) + { + return new GetLibraryPathTemplatePartsQuery(libraryType ?? "Music"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandFixture.cs index 2739e804..db298d6b 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandFixture.cs @@ -19,8 +19,9 @@ public class RecoverPasswordCommandFixture /// /// Optional. The username. /// Optional. The TOTP code. + /// Whether the TOTP code should be included, or forced to . /// The created command. - public RecoverPasswordCommand Create(string? username = null, string? totpCode = null) + public RecoverPasswordCommand Create(string? username = null, string? totpCode = null, bool includeTotpCode = true) { return new Faker() .CustomInstantiator(f => new RecoverPasswordCommand( @@ -28,7 +29,7 @@ public class RecoverPasswordCommandFixture default! )) .RuleFor(x => x.Username, f => username ?? f.Person.UserName) - .RuleFor(x => x.TotpCode, f => totpCode ?? f.Random.Replace("######")); + .RuleFor(x => x.TotpCode, f => includeTotpCode ? (totpCode ?? f.Random.Replace("######")) : null); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs index 30a02076..96461251 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs @@ -20,13 +20,16 @@ public class LoginUserQueryFixture /// Optional. The username. /// Optional. The password. /// Whether the TOTP code should be included, or forced to . + /// Optional. The TOTP code. When provided, the TOTP code is included even if is . /// The created query. public LoginUserQuery Create( string? username = null, string? password = null, - bool includeTotpCode = false) + bool includeTotpCode = false, + string? totpCode = null) { string resolvedPassword = password ?? "Abcd123$"; + bool shouldIncludeTotpCode = includeTotpCode || totpCode is not null; Faker faker = new Faker() .CustomInstantiator(f => new LoginUserQuery( default!, @@ -36,8 +39,8 @@ public class LoginUserQueryFixture .RuleFor(x => x.Username, f => username ?? f.Person.UserName) .RuleFor(x => x.Password, resolvedPassword); - if (includeTotpCode) - faker.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits + if (shouldIncludeTotpCode) + faker.RuleFor(x => x.TotpCode, f => totpCode ?? f.Random.Replace("######")); // generates 6 random digits when no code is pinned return faker.Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandFixture.cs index 2c6d7efc..756905c3 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandFixture.cs @@ -22,19 +22,23 @@ public class UpdateUserRoleAndPermissionsCommandFixture /// Optional. The role Id to assign. If null, no role will be assigned. /// Optional. The permission Ids to assign. /// The number of permissions to generate when none are provided. + /// Whether the permissions should be included, or forced to . /// The created command. public UpdateUserRoleAndPermissionsCommand Create( Guid? userId = null, Guid? roleId = null, IEnumerable? permissions = null, - int permissionCount = 3) + int permissionCount = 3, + bool includePermissions = true) { return new Faker() .CustomInstantiator(f => new UpdateUserRoleAndPermissionsCommand( userId ?? Guid.NewGuid(), roleId, default!)) - .RuleFor(x => x.Permissions, f => [.. permissions ?? Enumerable.Range(0, permissionCount).Select(_ => Guid.NewGuid())]) + .RuleFor(x => x.Permissions, f => includePermissions + ? [.. permissions ?? Enumerable.Range(0, permissionCount).Select(_ => Guid.NewGuid())] + : null!) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryFixture.cs index 59013332..8e2da36a 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryFixture.cs @@ -19,12 +19,13 @@ public class GetUserPermissionsQueryFixture /// Creates a random valid query to get user permissions. /// /// Optional. The user Id. + /// Whether the user Id should be included, or forced to . /// The created query. - public GetUserPermissionsQuery Create(Guid? userId = null) + public GetUserPermissionsQuery Create(Guid? userId = null, bool includeUserId = true) { return new Faker() .CustomInstantiator(f => new GetUserPermissionsQuery( - userId ?? Guid.NewGuid())) + includeUserId ? (userId ?? Guid.NewGuid()) : null)) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryFixture.cs index a9ffa0d9..313d6423 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryFixture.cs @@ -19,12 +19,13 @@ public class GetUserRoleQueryFixture /// Creates a random valid query to get a user's role. /// /// Optional. The user Id. + /// Whether the user Id should be included, or forced to . /// The created query. - public GetUserRoleQuery Create(Guid? userId = null) + public GetUserRoleQuery Create(Guid? userId = null, bool includeUserId = true) { return new Faker() .CustomInstantiator(f => new GetUserRoleQuery( - userId ?? Guid.NewGuid())) + includeUserId ? (userId ?? Guid.NewGuid()) : null)) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs index 83ebbd9a..36b56f5f 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs @@ -22,6 +22,7 @@ public class UpdateUserSettingsCommandFixture /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. /// Optional. Whether the theme data served to this user is cached, or not. /// Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. + /// Optional. Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Optional. Whether PDF books are rendered as page images for the user. /// Optional. Whether the styles of the book content are preserved when it is rendered for the user. /// The created command. @@ -31,16 +32,18 @@ public class UpdateUserSettingsCommandFixture bool? shouldIgnoreThePrefixForAlphaPicker = null, bool? isThemeCachingEnabled = null, bool? shouldAggregateMetadataWhenMissing = null, + bool? shouldAggregateArtworkWhenMissing = null, bool? shouldRenderPdfAsImages = null, bool? shouldPreserveBookStyles = null) { return new Faker() - .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default, default, default, default)) + .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default, default, default, default, default)) .RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool()) .RuleFor(x => x.ItemsPerPage, f => itemsPerPage ?? f.Random.Int(1, 100)) .RuleFor(x => x.ShouldIgnoreThePrefixForAlphaPicker, f => shouldIgnoreThePrefixForAlphaPicker ?? f.Random.Bool()) .RuleFor(x => x.IsThemeCachingEnabled, f => isThemeCachingEnabled ?? f.Random.Bool()) .RuleFor(x => x.ShouldAggregateMetadataWhenMissing, f => shouldAggregateMetadataWhenMissing ?? f.Random.Bool()) + .RuleFor(x => x.ShouldAggregateArtworkWhenMissing, f => shouldAggregateArtworkWhenMissing ?? f.Random.Bool()) .RuleFor(x => x.ShouldRenderPdfAsImages, f => shouldRenderPdfAsImages ?? f.Random.Bool()) .RuleFor(x => x.ShouldPreserveBookStyles, f => shouldPreserveBookStyles ?? f.Random.Bool()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj b/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj index 595cbfba..e129f51c 100644 --- a/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj +++ b/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs index 54f61ead..060ae549 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -18,12 +19,16 @@ public class ArtworkDtoFixture /// /// Optional. The local file system path of the artwork. /// Optional. The remote URL of the artwork. + /// Optional. The type of the artwork. + /// Optional. The ordinal of the artwork within its type. /// The created . public ArtworkDto Create( string? localPath = null, - string? remoteUrl = null) + string? remoteUrl = null, + ArtworkType type = ArtworkType.Cover, + int ordinal = 0) { - return new ArtworkDto(localPath, remoteUrl); + return new ArtworkDto(type, ordinal, localPath, remoteUrl); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/Pagination/PaginationDataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/Pagination/PaginationDataDtoFixture.cs new file mode 100644 index 00000000..ee5c525c --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/Pagination/PaginationDataDtoFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common.Pagination; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common.Pagination; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PaginationDataDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The current page number in a paginated collection. + /// Optional. The number of items to include per page in paginated results. + /// Whether the current page should be included, or left at its default value. + /// Whether the per page count should be included, or left at its default value. + /// The created . + public PaginationDataDto Create( + int? currentPage = null, + int? perPage = null, + bool includeCurrentPage = true, + bool includePerPage = true) + { + PaginationDataDto dto = new(); + if (includeCurrentPage) + dto.CurrentPage = currentPage ?? _faker.Random.Int(1, 100); + if (includePerPage) + dto.PerPage = perPage ?? _faker.Random.Int(1, 200); + return dto; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs index e9d5bc34..000dec79 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs @@ -16,6 +16,7 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; public class MediaContributorDtoFixture { private readonly Faker _faker = new(); + private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new(); /// /// Creates a random valid . @@ -38,9 +39,12 @@ public class MediaContributorDtoFixture bool includeRole = true) { return new MediaContributorDto( - Name: includeName ? new MediaContributorNameDto( - DisplayName: includeDisplayName ? displayName ?? _faker.Name.FullName() : null, - LegalName: includeLegalName ? legalName : null) : null, + Name: includeName ? _mediaContributorNameDtoFixture.Create( + displayName: displayName, + legalName: legalName, + includeDisplayName: includeDisplayName, + // this fixture historically left the legal name null unless one was explicitly supplied, so the name fixture is only asked for one when a value is passed + includeLegalName: includeLegalName && legalName is not null) : null, Role: includeRole ? role ?? _faker.PickRandom() : null); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs index a332a8a7..812d8663 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs @@ -21,14 +21,18 @@ public class MediaContributorNameDtoFixture /// /// Optional. The display name of the media contributor. /// Optional. The legal name of the media contributor. + /// Whether the display name should be included, or forced to . + /// Whether the legal name should be included, or forced to . /// The created . public MediaContributorNameDto Create( string? displayName = null, - string? legalName = null) + string? legalName = null, + bool includeDisplayName = true, + bool includeLegalName = true) { return new MediaContributorNameDto( - displayName ?? _faker.Name.FullName(), - legalName ?? _faker.Name.FullName()); + includeDisplayName ? displayName ?? _faker.Name.FullName() : null, + includeLegalName ? legalName ?? _faker.Name.FullName() : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs index bc52b188..1eb8dc40 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs @@ -1,8 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; @@ -27,74 +31,145 @@ public class AlbumMetadataDtoFixture private readonly TagDtoFixture _tagDtoFixture = new(); private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); /// /// Creates a random valid . /// /// Optional. The title of the album. /// Optional. The original title of the album. + /// Optional. The title of the specific release (edition) of the album. /// Optional. A brief description or summary of the album. + /// Optional. The disambiguation comment of the album. /// Optional. The release information of the album. /// Optional. The language of the album. /// Optional. The original language of the album. /// Optional. The tags that describe or categorize the album. /// Optional. The genres associated with the album. - /// Optional. The type of the release. + /// Optional. The script used by the language of the release of the album. + /// Optional. The types of the release. /// Optional. The status of the release. + /// Optional. The physical or digital medium of the album. + /// Optional. The outermost physical packaging of the album. /// Optional. The number of discs of the release. /// Optional. The number of tracks of the release. + /// Optional. The barcode of the album. + /// Optional. The catalog number of the album. + /// Optional. The name of the label that issued the album. + /// Optional. The ASIN of the album. + /// Optional. The MusicBrainz identifier of the release. + /// Optional. The MusicBrainz identifier of the release group. + /// Optional. The MusicBrainz identifier of the release artist. + /// Optional. The media contributors that performed on the album. + /// Optional. The ratings of the album. /// Whether the title should be included, or forced to . /// Whether the original title should be included, or forced to . /// Whether the description should be included, or forced to . + /// Whether the disambiguation should be included, or forced to . /// Whether the release information should be included, or forced to . /// Whether the language should be included, or forced to . /// Whether the original language should be included, or forced to . /// Whether the tags should be included, or forced to . /// Whether the genres should be included, or forced to . - /// Whether the release type should be included, or forced to . + /// Whether the script should be included, or forced to . + /// Whether the release types should be included, or forced to . /// Whether the release status should be included, or forced to . + /// Whether the media format should be included, or forced to . + /// Whether the packaging should be included, or forced to . /// Whether the total number of discs should be included, or forced to . /// Whether the total number of tracks should be included, or forced to . + /// Whether the barcode should be included, or forced to . + /// Whether the catalog number should be included, or forced to . + /// Whether the label should be included, or forced to . + /// Whether the ASIN should be included, or forced to . + /// Whether the MusicBrainz release Id should be included, or forced to . + /// Whether the MusicBrainz release group Id should be included, or forced to . + /// Whether the MusicBrainz release artist Id should be included, or forced to . + /// Whether the contributors should be included, or forced to . + /// Whether the ratings should be included, or forced to . /// The created . public AlbumMetadataDto Create( string? title = null, string? originalTitle = null, + string? releaseTitle = null, string? description = null, + string? disambiguation = null, ReleaseInfoDto? releaseInfo = null, LanguageInfoDto? language = null, LanguageInfoDto? originalLanguage = null, List? tags = null, List? genres = null, - MusicReleaseType? releaseType = null, + string? script = null, + List? releaseTypes = null, MusicReleaseStatus? releaseStatus = null, + MusicMediaFormat? mediaFormat = null, + MusicReleasePackaging? packaging = null, int? totalDiscs = null, int? totalTracks = null, + string? barcode = null, + List? catalogNumbers = null, + string? label = null, + string? asin = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseArtistId = null, + List? contributors = null, + List? ratings = null, bool includeTitle = true, bool includeOriginalTitle = true, bool includeDescription = true, + bool includeDisambiguation = true, bool includeReleaseInfo = true, bool includeLanguage = true, bool includeOriginalLanguage = true, bool includeTags = true, bool includeGenres = true, - bool includeReleaseType = true, + bool includeScript = true, + bool includeReleaseTypes = true, bool includeReleaseStatus = true, + bool includeMediaFormat = true, + bool includePackaging = true, bool includeTotalDiscs = true, - bool includeTotalTracks = true) + bool includeTotalTracks = true, + bool includeBarcode = true, + bool includeCatalogNumbers = true, + bool includeLabel = true, + bool includeAsin = true, + bool includeMusicBrainzReleaseId = true, + bool includeMusicBrainzReleaseGroupId = true, + bool includeMusicBrainzReleaseArtistId = true, + bool includeContributors = true, + bool includeRatings = true, + bool includeReleaseTitle = true) { return new AlbumMetadataDto( includeTitle ? (title ?? _faker.Music.Genre()) : null, includeOriginalTitle ? (originalTitle ?? _faker.Music.Genre()) : null, includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null, + includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null, includeReleaseInfo ? (releaseInfo ?? GenerateReleaseInfo()) : null, includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null, includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null, includeTags ? (tags ?? GenerateDistinctTags()) : null, includeGenres ? (genres ?? GenerateDistinctGenres()) : null, - includeReleaseType ? (releaseType ?? _faker.PickRandom()) : null, + includeScript ? (script ?? _faker.Random.String2(4)) : null, + includeReleaseTypes ? (releaseTypes ?? [_faker.PickRandom()]) : null, includeReleaseStatus ? (releaseStatus ?? _faker.PickRandom()) : null, + includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includePackaging ? (packaging ?? _faker.PickRandom()) : null, includeTotalDiscs ? (totalDiscs ?? _faker.Random.Int(1, 3)) : null, - includeTotalTracks ? (totalTracks ?? _faker.Random.Int(1, 30)) : null); + includeTotalTracks ? (totalTracks ?? _faker.Random.Int(1, 30)) : null, + includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, + includeCatalogNumbers ? (catalogNumbers ?? [_faker.Random.AlphaNumeric(10)]) : null, + includeLabel ? (label ?? _faker.Company.CompanyName()) : null, + includeAsin ? (asin ?? _faker.Random.AlphaNumeric(10)) : null, + includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, + includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, + includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? _mediaContributorDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeReleaseTitle ? (releaseTitle ?? _faker.Commerce.ProductName()) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataLookupDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataLookupDtoFixture.cs new file mode 100644 index 00000000..74906561 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataLookupDtoFixture.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AlbumMetadataLookupDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the album belongs to. + /// Optional. The file system path of a track of the album. + /// Optional. The MusicBrainz identifier of the release group of the album. + /// Optional. The MusicBrainz identifier of the release of the album. + /// Optional. The title of the album. + /// Optional. The name of the artist of the album. + /// Optional. The year the album was released. + /// Optional. The number of tracks the local album has. + /// The created . + public AlbumMetadataLookupDto Create( + Guid? libraryId = null, + string? path = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseId = null, + string? title = null, + string? artistName = null, + int? releaseYear = null, + int? trackCount = null) + { + return new AlbumMetadataLookupDto( + libraryId ?? Guid.NewGuid(), + path ?? _faker.System.FilePath(), + musicBrainzReleaseGroupId, + musicBrainzReleaseId, + title, + artistName, + releaseYear, + trackCount); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataDtoFixture.cs new file mode 100644 index 00000000..edf9c7a0 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataDtoFixture.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtistMetadataDtoFixture +{ + private const int MINIMUM_LIFESPAN_YEAR = 1900; + private const int MAXIMUM_LIFESPAN_YEAR = 2026; + + private readonly Faker _faker = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly MusicAreaDtoFixture _musicAreaDtoFixture = new(); + private readonly MusicArtistAliasDtoFixture _musicArtistAliasDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the artist. + /// Optional. The sort name of the artist. + /// Optional. The disambiguation comment of the artist. + /// Optional. The type of the artist. + /// Optional. The gender of the artist. + /// Optional. The ISO 3166-1 alpha-2 code of the country of the artist. + /// Optional. The area the artist is primarily identified with. + /// Optional. The area the artist began in. + /// Optional. The area the artist ended in. + /// Optional. The date the artist started existing. + /// Optional. The date the artist stopped existing. + /// Optional. Whether the artist no longer exists. + /// Optional. The website of the artist. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The ISNI codes of the artist. + /// Optional. The alternative names of the artist. + /// Optional. The genres associated with the artist. + /// Optional. The tags that describe or categorize the artist. + /// Optional. The ratings of the artist. + /// Optional. The media contributors that make up the artist. + /// Whether the name should be included, or forced to . + /// Whether the sort name should be included, or forced to . + /// Whether the disambiguation should be included, or forced to . + /// Whether the type should be included, or forced to . + /// Whether the gender should be included, or forced to . + /// Whether the country should be included, or forced to . + /// Whether the area should be included, or forced to . + /// Whether the begin area should be included, or forced to . + /// Whether the end area should be included, or forced to . + /// Whether the lifespan begin should be included, or forced to . + /// Whether the lifespan end should be included, or forced to . + /// Whether the website should be included, or forced to . + /// Whether the MusicBrainz artist Id should be included, or forced to . + /// Whether the IPI codes should be included, or forced to . + /// Whether the ISNI codes should be included, or forced to . + /// Whether the genres should be included, or forced to . + /// Whether the tags should be included, or forced to . + /// Whether the aliases should be included, or forced to . + /// Whether the ratings should be included, or forced to . + /// Whether the contributors should be included, or forced to . + /// The created . + public ArtistMetadataDto Create( + string? name = null, + string? sortName = null, + string? disambiguation = null, + MusicArtistType? type = null, + MusicArtistGender? gender = null, + string? country = null, + MusicAreaDto? area = null, + MusicAreaDto? beginArea = null, + MusicAreaDto? endArea = null, + DateOnly? lifeSpanBegin = null, + DateOnly? lifeSpanEnd = null, + bool? isEnded = null, + string? website = null, + Guid? musicBrainzArtistId = null, + List? ipis = null, + List? isnis = null, + List? aliases = null, + List? genres = null, + List? tags = null, + List? ratings = null, + List? contributors = null, + bool includeName = true, + bool includeSortName = true, + bool includeDisambiguation = true, + bool includeType = true, + bool includeGender = true, + bool includeCountry = true, + bool includeArea = true, + bool includeBeginArea = true, + bool includeEndArea = true, + bool includeLifeSpanBegin = true, + bool includeLifeSpanEnd = true, + bool includeWebsite = true, + bool includeMusicBrainzArtistId = true, + bool includeIpis = true, + bool includeIsnis = true, + bool includeGenres = true, + bool includeTags = true, + bool includeAliases = true, + bool includeRatings = true, + bool includeContributors = true) + { + int lifeSpanBeginYear = Random.Shared.Next(MINIMUM_LIFESPAN_YEAR, MAXIMUM_LIFESPAN_YEAR); + int lifeSpanEndYear = Random.Shared.Next(lifeSpanBeginYear, Math.Max(lifeSpanBeginYear + 1, MAXIMUM_LIFESPAN_YEAR)); + return new ArtistMetadataDto( + includeName ? (name ?? _faker.Name.FullName()) : null, + includeSortName ? (sortName ?? _faker.Name.FullName()) : null, + includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null, + includeType ? (type ?? _faker.PickRandom()) : null, + includeGender ? (gender ?? _faker.PickRandom()) : null, + includeCountry ? (country ?? _faker.Address.CountryCode()) : null, + includeArea ? (area ?? _musicAreaDtoFixture.Create()) : null, + includeBeginArea ? (beginArea ?? _musicAreaDtoFixture.Create()) : null, + includeEndArea ? (endArea ?? _musicAreaDtoFixture.Create()) : null, + includeLifeSpanBegin ? (lifeSpanBegin ?? new DateOnly(lifeSpanBeginYear, 1, 1)) : null, + includeLifeSpanEnd ? (lifeSpanEnd ?? new DateOnly(lifeSpanEndYear, 1, 1)) : null, + isEnded ?? _faker.Random.Bool(), + includeWebsite ? (website ?? _faker.Internet.Url()) : null, + includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeIpis ? (ipis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(9))]) : null, + includeIsnis ? (isnis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(16))]) : null, + includeAliases ? (aliases ?? _musicArtistAliasDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeGenres ? (genres ?? _genreDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeTags ? (tags ?? _tagDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeContributors ? (contributors ?? _mediaContributorDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataLookupDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataLookupDtoFixture.cs new file mode 100644 index 00000000..5d7cc9f7 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/ArtistMetadataLookupDtoFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtistMetadataLookupDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the artist belongs to. + /// Optional. The file system path of a track of the artist. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The name of the artist. + /// The created . + public ArtistMetadataLookupDto Create( + Guid? libraryId = null, + string? path = null, + Guid? musicBrainzArtistId = null, + string? name = null) + { + return new ArtistMetadataLookupDto( + libraryId ?? Guid.NewGuid(), + path ?? _faker.System.FilePath(), + musicBrainzArtistId, + name); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs index c8eba087..bc191ac6 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs @@ -1,8 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; using System.Collections.Generic; @@ -26,6 +31,11 @@ public class AudioMetadataDtoFixture private readonly TagDtoFixture _tagDtoFixture = new(); private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); /// /// Creates a random valid . @@ -33,77 +43,135 @@ public class AudioMetadataDtoFixture /// Optional. The title of the audio. /// Optional. The original title of the audio. /// Optional. A brief description or summary of the audio. + /// Optional. The disambiguation comment of the audio. /// Optional. The release information of the audio. /// Optional. The language of the audio. /// Optional. The original language of the audio. /// Optional. The tags that describe or categorize the audio. /// Optional. The genres associated with the audio. + /// Optional. The script used by the language of the audio. + /// Optional. The musical key of the audio. + /// Optional. The tempo of the audio, in beats per minute. + /// Optional. Whether the recording of the audio is a video recording. + /// Optional. The work the audio is a recording of. + /// Optional. The ISRC codes of the audio. + /// Optional. The moods of the audio. /// Optional. The duration of the audio, in seconds. /// Optional. The sample rate of the audio, in Hz. /// Optional. The number of audio channels. /// Optional. The bit depth of the audio. /// Optional. The audio codec used. /// Optional. The bitrate of the audio, in kbps. + /// Optional. The MusicBrainz identifier of the recording. + /// Optional. The MusicBrainz identifier of the track. + /// Optional. The media contributors that performed on the audio. + /// Optional. The ratings of the audio. /// Whether the title should be included, or forced to . /// Whether the original title should be included, or forced to . /// Whether the description should be included, or forced to . + /// Whether the disambiguation should be included, or forced to . /// Whether the release information should be included, or forced to . /// Whether the language should be included, or forced to . /// Whether the original language should be included, or forced to . /// Whether the tags should be included, or forced to . /// Whether the genres should be included, or forced to . + /// Whether the script should be included, or forced to . + /// Whether the musical key should be included, or forced to . + /// Whether the tempo should be included, or forced to . + /// Whether the work should be included, or forced to . + /// Whether the ISRC codes should be included, or forced to . + /// Whether the moods should be included, or forced to . /// Whether the duration should be included, or forced to . /// Whether the sample rate should be included, or forced to . /// Whether the channels should be included, or forced to . /// Whether the bit depth should be included, or forced to . /// Whether the audio codec should be included, or forced to . /// Whether the bitrate should be included, or forced to . + /// Whether the MusicBrainz recording Id should be included, or forced to . + /// Whether the MusicBrainz track Id should be included, or forced to . + /// Whether the contributors should be included, or forced to . + /// Whether the ratings should be included, or forced to . /// The created . public AudioMetadataDto Create( string? title = null, string? originalTitle = null, string? description = null, + string? disambiguation = null, ReleaseInfoDto? releaseInfo = null, LanguageInfoDto? language = null, LanguageInfoDto? originalLanguage = null, List? tags = null, List? genres = null, + string? script = null, + MusicKey? key = null, + int? bpm = null, + bool? isVideo = null, + MusicWorkDto? work = null, + List? isrcs = null, + List? moods = null, int? durationInSeconds = null, int? sampleRate = null, int? channels = null, int? bitDepth = null, string? audioCodec = null, int? bitrate = null, + Guid? musicBrainzRecordingId = null, + Guid? musicBrainzTrackId = null, + List? contributors = null, + List? ratings = null, bool includeTitle = true, bool includeOriginalTitle = true, bool includeDescription = true, + bool includeDisambiguation = true, bool includeReleaseInfo = true, bool includeLanguage = true, bool includeOriginalLanguage = true, bool includeTags = true, bool includeGenres = true, + bool includeScript = true, + bool includeKey = true, + bool includeBpm = true, + bool includeWork = true, + bool includeIsrcs = true, + bool includeMoods = true, bool includeDurationInSeconds = true, bool includeSampleRate = true, bool includeChannels = true, bool includeBitDepth = true, bool includeAudioCodec = true, - bool includeBitrate = true) + bool includeBitrate = true, + bool includeMusicBrainzRecordingId = true, + bool includeMusicBrainzTrackId = true, + bool includeContributors = true, + bool includeRatings = true) { return new AudioMetadataDto( includeTitle ? (title ?? _faker.Music.Genre()) : null, includeOriginalTitle ? (originalTitle ?? _faker.Music.Genre()) : null, includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null, + includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null, includeReleaseInfo ? (releaseInfo ?? GenerateReleaseInfo()) : null, includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null, includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null, includeTags ? (tags ?? GenerateDistinctTags()) : null, includeGenres ? (genres ?? GenerateDistinctGenres()) : null, + includeScript ? (script ?? _faker.Random.String2(4)) : null, + includeKey ? (key ?? _faker.PickRandom()) : null, + includeBpm ? (bpm ?? _faker.Random.Int(40, 220)) : null, + isVideo ?? _faker.Random.Bool(), + includeWork ? (work ?? _musicWorkDtoFixture.Create()) : null, + includeIsrcs ? (isrcs ?? _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeMoods ? (moods ?? _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, includeDurationInSeconds ? (durationInSeconds ?? _faker.Random.Int(60, 7200)) : null, includeSampleRate ? (sampleRate ?? _faker.Random.Int(8000, 192000)) : null, includeChannels ? (channels ?? _faker.Random.Int(1, 8)) : null, includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null, includeAudioCodec ? (audioCodec ?? _faker.Random.ArrayElement(["FLAC", "MP3", "AAC", "ALAC"])) : null, - includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null); + includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null, + includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null, + includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? _mediaContributorDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAlbumMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAlbumMetadataDtoFixture.cs new file mode 100644 index 00000000..19e4b97b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAlbumMetadataDtoFixture.cs @@ -0,0 +1,179 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MusicAlbumMetadataDtoFixture +{ + private const int MINIMUM_RELEASE_YEAR = 1900; + private const int MAXIMUM_RELEASE_YEAR = 2026; + + private readonly Faker _faker = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the album. + /// Optional. The original title of the album. + /// Optional. The title of the specific release (edition) of the album. + /// Optional. A brief description or summary of the album. + /// Optional. The disambiguation comment of the album. + /// Optional. The release information of the album. + /// Optional. The language of the album. + /// Optional. The original language of the album. + /// Optional. The tags that describe or categorize the album. + /// Optional. The genres associated with the album. + /// Optional. The script used by the language of the release of the album. + /// Optional. The types of the release. + /// Optional. The status of the release. + /// Optional. The number of discs of the release. + /// Optional. The number of tracks of the release. + /// Whether the title should be included, or forced to . + /// Whether the original title should be included, or forced to . + /// Whether the description should be included, or forced to . + /// Whether the disambiguation should be included, or forced to . + /// Whether the release information should be included, or forced to . + /// Whether the language should be included, or forced to . + /// Whether the original language should be included, or forced to . + /// Whether the tags should be included, or forced to . + /// Whether the genres should be included, or forced to . + /// Whether the script should be included, or forced to . + /// Whether the release types should be included, or forced to . + /// Whether the release status should be included, or forced to . + /// Whether the total number of discs should be included, or forced to . + /// Whether the total number of tracks should be included, or forced to . + /// The created . + public MusicAlbumMetadataDto Create( + string? title = null, + string? originalTitle = null, + string? releaseTitle = null, + string? description = null, + string? disambiguation = null, + ReleaseInfoDto? releaseInfo = null, + LanguageInfoDto? language = null, + LanguageInfoDto? originalLanguage = null, + List? tags = null, + List? genres = null, + string? script = null, + List? releaseTypes = null, + MusicReleaseStatus? releaseStatus = null, + int? totalDiscs = null, + int? totalTracks = null, + bool includeTitle = true, + bool includeOriginalTitle = true, + bool includeDescription = true, + bool includeDisambiguation = true, + bool includeReleaseInfo = true, + bool includeLanguage = true, + bool includeOriginalLanguage = true, + bool includeTags = true, + bool includeGenres = true, + bool includeScript = true, + bool includeReleaseTypes = true, + bool includeReleaseStatus = true, + bool includeTotalDiscs = true, + bool includeTotalTracks = true, + bool includeReleaseTitle = true) + { + return new MusicAlbumMetadataDto( + includeTitle ? (title ?? _faker.Music.Genre()) : null, + includeOriginalTitle ? (originalTitle ?? _faker.Music.Genre()) : null, + includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null, + includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null, + includeReleaseInfo ? (releaseInfo ?? GenerateReleaseInfo()) : null, + includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null, + includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null, + includeTags ? (tags ?? GenerateDistinctTags()) : null, + includeGenres ? (genres ?? GenerateDistinctGenres()) : null, + includeScript ? (script ?? _faker.Random.String2(4)) : null, + includeReleaseTypes ? (releaseTypes ?? [_faker.PickRandom()]) : null, + includeReleaseStatus ? (releaseStatus ?? _faker.PickRandom()) : null, + includeTotalDiscs ? (totalDiscs ?? _faker.Random.Int(1, 3)) : null, + includeTotalTracks ? (totalTracks ?? _faker.Random.Int(1, 30)) : null, + includeReleaseTitle ? (releaseTitle ?? _faker.Commerce.ProductName()) : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates a random valid with consistent dates and years. + /// + /// The created . + private ReleaseInfoDto GenerateReleaseInfo() + { + int originalReleaseYear = Random.Shared.Next(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR); + int reReleaseYear = Random.Shared.Next(originalReleaseYear, MAXIMUM_RELEASE_YEAR); + return _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(originalReleaseYear, 1, 1), + originalReleaseYear: originalReleaseYear, + reReleaseDate: new DateOnly(reReleaseYear, 1, 1), + reReleaseYear: reReleaseYear, + releaseCountry: _faker.PickRandom(), + releaseVersion: _faker.Random.String2(_faker.Random.Number(1, 50))); + } + + /// + /// Creates two genres with distinct names, so that the storage deduplication never collapses them into one. + /// + /// The created genres. + private List GenerateDistinctGenres() + { + return + [ + _genreDtoFixture.Create(name: CreateUniqueName()), + _genreDtoFixture.Create(name: CreateUniqueName()) + ]; + } + + /// + /// Creates two tags with distinct names, so that the storage deduplication never collapses them into one. + /// + /// The created tags. + private List GenerateDistinctTags() + { + return + [ + _tagDtoFixture.Create(name: CreateUniqueName()), + _tagDtoFixture.Create(name: CreateUniqueName()) + ]; + } + + /// + /// Creates a unique name, so that the generated genres and tags never collapse into one after storage deduplication. + /// + /// A unique name of at most 50 characters. + private string CreateUniqueName() + { + string uniqueSuffix = Guid.NewGuid().ToString("N")[..12]; + int maximumWordLength = 50 - uniqueSuffix.Length - 1; + string word = _faker.Lorem.Word(); + string truncatedWord = word.Length > maximumWordLength ? word[..maximumWordLength] : word; + return $"{truncatedWord}-{uniqueSuffix}"; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaDtoFixture.cs new file mode 100644 index 00000000..2f751b28 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicAreaDtoFixture.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MusicAreaDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The MusicBrainz identifier of the area. + /// Optional. The name of the area. + /// Optional. The sort name of the area. + /// Optional. The disambiguation comment of the area. + /// Optional. The MusicBrainz type of the area. + /// Optional. The ISO 3166 code of the area. + /// Whether the MusicBrainz area Id should be included, or forced to . + /// Whether the name should be included, or forced to . + /// Whether the sort name should be included, or forced to . + /// Whether the disambiguation should be included, or forced to . + /// Whether the type should be included, or forced to . + /// Whether the ISO 3166 code should be included, or forced to . + /// The created . + public MusicAreaDto Create( + Guid? musicBrainzAreaId = null, + string? name = null, + string? sortName = null, + string? disambiguation = null, + string? type = null, + string? iso3166Code = null, + bool includeMusicBrainzAreaId = true, + bool includeName = true, + bool includeSortName = true, + bool includeDisambiguation = true, + bool includeType = true, + bool includeIso3166Code = true) + { + return new MusicAreaDto( + includeMusicBrainzAreaId ? (musicBrainzAreaId ?? _faker.Random.Guid()) : null, + includeName ? (name ?? _faker.Address.Country()) : null, + includeSortName ? (sortName ?? _faker.Address.Country()) : null, + includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null, + includeType ? (type ?? _faker.Random.ArrayElement(["Country", "City", "Area"])) : null, + includeIso3166Code ? (iso3166Code ?? _faker.Address.CountryCode()) : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistAliasDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistAliasDtoFixture.cs new file mode 100644 index 00000000..2b59d2aa --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistAliasDtoFixture.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MusicArtistAliasDtoFixture +{ + private const int MINIMUM_ALIAS_YEAR = 1900; + private const int MAXIMUM_ALIAS_YEAR = 2026; + + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the alias. + /// Optional. The sort name of the alias. + /// Optional. The type of the alias. + /// Optional. The locale the alias is used in. + /// Optional. Whether this is the primary alias of the artist. + /// Optional. The date the alias began being used. + /// Optional. The date the alias stopped being used. + /// Optional. Whether the alias is no longer used. + /// Whether the name should be included, or forced to . + /// Whether the sort name should be included, or forced to . + /// Whether the type should be included, or forced to . + /// Whether the locale should be included, or forced to . + /// Whether the begin date should be included, or forced to . + /// Whether the end date should be included, or forced to . + /// The created . + public MusicArtistAliasDto Create( + string? name = null, + string? sortName = null, + string? type = null, + string? locale = null, + bool? isPrimary = null, + DateOnly? beginDate = null, + DateOnly? endDate = null, + bool? isEnded = null, + bool includeName = true, + bool includeSortName = true, + bool includeType = true, + bool includeLocale = true, + bool includeBeginDate = true, + bool includeEndDate = true) + { + int beginYear = Random.Shared.Next(MINIMUM_ALIAS_YEAR, MAXIMUM_ALIAS_YEAR); + int endYear = Random.Shared.Next(beginYear, Math.Max(beginYear + 1, MAXIMUM_ALIAS_YEAR)); + return new MusicArtistAliasDto( + includeName ? (name ?? _faker.Name.FullName()) : null, + includeSortName ? (sortName ?? _faker.Name.FullName()) : null, + includeType ? (type ?? _faker.Random.ArrayElement(["Artist name", "Search hint"])) : null, + includeLocale ? (locale ?? _faker.Random.String2(2)) : null, + isPrimary ?? _faker.Random.Bool(), + includeBeginDate ? (beginDate ?? new DateOnly(beginYear, 1, 1)) : null, + includeEndDate ? (endDate ?? new DateOnly(endYear, 1, 1)) : null, + isEnded ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistMetadataDtoFixture.cs new file mode 100644 index 00000000..16e1a77f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtistMetadataDtoFixture.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MusicArtistMetadataDtoFixture +{ + private const int MINIMUM_LIFESPAN_YEAR = 1900; + private const int MAXIMUM_LIFESPAN_YEAR = 2026; + + private readonly Faker _faker = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly MusicAreaDtoFixture _musicAreaDtoFixture = new(); + private readonly MusicArtistAliasDtoFixture _musicArtistAliasDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the artist. + /// Optional. The sort name of the artist. + /// Optional. The disambiguation comment of the artist. + /// Optional. The type of the artist. + /// Optional. The gender of the artist. + /// Optional. The ISO 3166-1 alpha-2 code of the country of the artist. + /// Optional. The area the artist is primarily identified with. + /// Optional. The area the artist began in. + /// Optional. The area the artist ended in. + /// Optional. The date the artist started existing. + /// Optional. The date the artist stopped existing. + /// Optional. Whether the artist no longer exists. + /// Optional. The genres associated with the artist. + /// Optional. The tags that describe or categorize the artist. + /// Optional. The alternative names of the artist. + /// Whether the name should be included, or forced to . + /// Whether the sort name should be included, or forced to . + /// Whether the disambiguation should be included, or forced to . + /// Whether the type should be included, or forced to . + /// Whether the gender should be included, or forced to . + /// Whether the country should be included, or forced to . + /// Whether the area should be included, or forced to . + /// Whether the begin area should be included, or forced to . + /// Whether the end area should be included, or forced to . + /// Whether the lifespan begin should be included, or forced to . + /// Whether the lifespan end should be included, or forced to . + /// Whether the genres should be included, or forced to . + /// Whether the tags should be included, or forced to . + /// Whether the aliases should be included, or forced to . + /// The created . + public MusicArtistMetadataDto Create( + string? name = null, + string? sortName = null, + string? disambiguation = null, + MusicArtistType? type = null, + MusicArtistGender? gender = null, + string? country = null, + MusicAreaDto? area = null, + MusicAreaDto? beginArea = null, + MusicAreaDto? endArea = null, + DateOnly? lifeSpanBegin = null, + DateOnly? lifeSpanEnd = null, + bool? isEnded = null, + List? genres = null, + List? tags = null, + List? aliases = null, + bool includeName = true, + bool includeSortName = true, + bool includeDisambiguation = true, + bool includeType = true, + bool includeGender = true, + bool includeCountry = true, + bool includeArea = true, + bool includeBeginArea = true, + bool includeEndArea = true, + bool includeLifeSpanBegin = true, + bool includeLifeSpanEnd = true, + bool includeGenres = true, + bool includeTags = true, + bool includeAliases = true) + { + int lifeSpanBeginYear = Random.Shared.Next(MINIMUM_LIFESPAN_YEAR, MAXIMUM_LIFESPAN_YEAR); + int lifeSpanEndYear = Random.Shared.Next(lifeSpanBeginYear, Math.Max(lifeSpanBeginYear + 1, MAXIMUM_LIFESPAN_YEAR)); + return new MusicArtistMetadataDto( + includeName ? (name ?? _faker.Name.FullName()) : null, + includeSortName ? (sortName ?? _faker.Name.FullName()) : null, + includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null, + includeType ? (type ?? _faker.PickRandom()) : null, + includeGender ? (gender ?? _faker.PickRandom()) : null, + includeCountry ? (country ?? _faker.Address.CountryCode()) : null, + includeArea ? (area ?? _musicAreaDtoFixture.Create()) : null, + includeBeginArea ? (beginArea ?? _musicAreaDtoFixture.Create()) : null, + includeEndArea ? (endArea ?? _musicAreaDtoFixture.Create()) : null, + includeLifeSpanBegin ? (lifeSpanBegin ?? new DateOnly(lifeSpanBeginYear, 1, 1)) : null, + includeLifeSpanEnd ? (lifeSpanEnd ?? new DateOnly(lifeSpanEndYear, 1, 1)) : null, + isEnded ?? _faker.Random.Bool(), + includeGenres ? (genres ?? _genreDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeTags ? (tags ?? _tagDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeAliases ? (aliases ?? _musicArtistAliasDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicTrackMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicTrackMetadataDtoFixture.cs new file mode 100644 index 00000000..91e8f0c4 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicTrackMetadataDtoFixture.cs @@ -0,0 +1,182 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MusicTrackMetadataDtoFixture +{ + private const int MINIMUM_RELEASE_YEAR = 1900; + private const int MAXIMUM_RELEASE_YEAR = 2026; + + private readonly Faker _faker = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the track. + /// Optional. The original title of the track. + /// Optional. A brief description or summary of the track. + /// Optional. The disambiguation comment of the track. + /// Optional. The release information of the track. + /// Optional. The language of the track. + /// Optional. The original language of the track. + /// Optional. The tags that describe or categorize the track. + /// Optional. The genres associated with the track. + /// Optional. Whether the recording of the track is a video recording. + /// Optional. The duration of the track, in seconds. + /// Optional. The sample rate of the track, in Hz. + /// Optional. The number of audio channels. + /// Optional. The bit depth of the track. + /// Optional. The audio codec used. + /// Optional. The bitrate of the track, in kbps. + /// Whether the title should be included, or forced to . + /// Whether the original title should be included, or forced to . + /// Whether the description should be included, or forced to . + /// Whether the disambiguation should be included, or forced to . + /// Whether the release information should be included, or forced to . + /// Whether the language should be included, or forced to . + /// Whether the original language should be included, or forced to . + /// Whether the tags should be included, or forced to . + /// Whether the genres should be included, or forced to . + /// Whether the duration should be included, or forced to . + /// Whether the sample rate should be included, or forced to . + /// Whether the channels should be included, or forced to . + /// Whether the bit depth should be included, or forced to . + /// Whether the audio codec should be included, or forced to . + /// Whether the bitrate should be included, or forced to . + /// The created . + public MusicTrackMetadataDto Create( + string? title = null, + string? originalTitle = null, + string? description = null, + string? disambiguation = null, + ReleaseInfoDto? releaseInfo = null, + LanguageInfoDto? language = null, + LanguageInfoDto? originalLanguage = null, + List? tags = null, + List? genres = null, + bool? isVideo = null, + int? durationInSeconds = null, + int? sampleRate = null, + int? channels = null, + int? bitDepth = null, + string? audioCodec = null, + int? bitrate = null, + bool includeTitle = true, + bool includeOriginalTitle = true, + bool includeDescription = true, + bool includeDisambiguation = true, + bool includeReleaseInfo = true, + bool includeLanguage = true, + bool includeOriginalLanguage = true, + bool includeTags = true, + bool includeGenres = true, + bool includeDurationInSeconds = true, + bool includeSampleRate = true, + bool includeChannels = true, + bool includeBitDepth = true, + bool includeAudioCodec = true, + bool includeBitrate = true) + { + return new MusicTrackMetadataDto( + includeTitle ? (title ?? _faker.Music.Genre()) : null, + includeOriginalTitle ? (originalTitle ?? _faker.Music.Genre()) : null, + includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null, + includeDisambiguation ? (disambiguation ?? _faker.Lorem.Sentence()) : null, + includeReleaseInfo ? (releaseInfo ?? GenerateReleaseInfo()) : null, + includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null, + includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null, + includeTags ? (tags ?? GenerateDistinctTags()) : null, + includeGenres ? (genres ?? GenerateDistinctGenres()) : null, + isVideo ?? _faker.Random.Bool(), + includeDurationInSeconds ? (durationInSeconds ?? _faker.Random.Int(60, 7200)) : null, + includeSampleRate ? (sampleRate ?? _faker.Random.Int(8000, 192000)) : null, + includeChannels ? (channels ?? _faker.Random.Int(1, 8)) : null, + includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null, + includeAudioCodec ? (audioCodec ?? _faker.Random.ArrayElement(["FLAC", "MP3", "AAC", "ALAC"])) : null, + includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates a random valid with consistent dates and years. + /// + /// The created . + private ReleaseInfoDto GenerateReleaseInfo() + { + int originalReleaseYear = Random.Shared.Next(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR); + int reReleaseYear = Random.Shared.Next(originalReleaseYear, MAXIMUM_RELEASE_YEAR); + return _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(originalReleaseYear, 1, 1), + originalReleaseYear: originalReleaseYear, + reReleaseDate: new DateOnly(reReleaseYear, 1, 1), + reReleaseYear: reReleaseYear, + releaseCountry: _faker.PickRandom(), + releaseVersion: _faker.Random.String2(_faker.Random.Number(1, 50))); + } + + /// + /// Creates two genres with distinct names, so that the storage deduplication never collapses them into one. + /// + /// The created genres. + private List GenerateDistinctGenres() + { + return + [ + _genreDtoFixture.Create(name: CreateUniqueName()), + _genreDtoFixture.Create(name: CreateUniqueName()) + ]; + } + + /// + /// Creates two tags with distinct names, so that the storage deduplication never collapses them into one. + /// + /// The created tags. + private List GenerateDistinctTags() + { + return + [ + _tagDtoFixture.Create(name: CreateUniqueName()), + _tagDtoFixture.Create(name: CreateUniqueName()) + ]; + } + + /// + /// Creates a unique name, so that the generated genres and tags never collapse into one after storage deduplication. + /// + /// A unique name of at most 50 characters. + private string CreateUniqueName() + { + string uniqueSuffix = Guid.NewGuid().ToString("N")[..12]; + int maximumWordLength = 50 - uniqueSuffix.Length - 1; + string word = _faker.Lorem.Word(); + string truncatedWord = word.Length > maximumWordLength ? word[..maximumWordLength] : word; + return $"{truncatedWord}-{uniqueSuffix}"; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicWorkDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicWorkDtoFixture.cs new file mode 100644 index 00000000..65a6b547 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/MusicWorkDtoFixture.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MusicWorkDtoFixture +{ + private readonly Faker _faker = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The MusicBrainz identifier of the work. + /// Optional. The title of the work. + /// Optional. The MusicBrainz type of the work. + /// Optional. The list of languages of the work. + /// Optional. The list of ISWC of the work. + /// Whether the MusicBrainz work Id should be included, or forced to . + /// Whether the title should be included, or forced to . + /// Whether the type should be included, or forced to . + /// Whether the languages should be included, or forced to . + /// Whether the ISWCs should be included, or forced to . + /// The created . + public MusicWorkDto Create( + Guid? musicBrainzWorkId = null, + string? title = null, + string? type = null, + List? languages = null, + List? iswcs = null, + bool includeMusicBrainzWorkId = true, + bool includeTitle = true, + bool includeType = true, + bool includeLanguages = true, + bool includeIswcs = true) + { + return new MusicWorkDto( + includeMusicBrainzWorkId ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null, + includeTitle ? (title ?? _faker.Music.Genre()) : null, + includeType ? (type ?? _faker.Random.ArrayElement(["Song", "Instrumental"])) : null, + includeLanguages ? (languages ?? _languageInfoDtoFixture.CreateMany(_faker.Random.Int(1, 2))) : null, + includeIswcs ? (iswcs ?? GenerateIswcs()) : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates a list of random ISWC codes. + /// + /// The generated ISWC codes. + private List GenerateIswcs() + { + return [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => $"T{_faker.Random.AlphaNumeric(10)}")]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/TrackMetadataLookupDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/TrackMetadataLookupDtoFixture.cs new file mode 100644 index 00000000..cca0c71d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/TrackMetadataLookupDtoFixture.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TrackMetadataLookupDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the track belongs to. + /// Optional. The file system path of the track. + /// Optional. The MusicBrainz identifier of the recording of the track. + /// Optional. The ISRC of the track. + /// Optional. The title of the track. + /// Optional. The name of the artist of the track. + /// Optional. The name of the release the track belongs to. + /// Optional. The number of the track on its disc. + /// Optional. The duration of the track in seconds. + /// Optional. The MusicBrainz identifier of the release the track belongs to. + /// Optional. The number of the disc the track belongs to. + /// Optional. The MusicBrainz identifier of the work the track is a recording of. + /// Optional. The title of the work the track is a recording of. + /// The created . + public TrackMetadataLookupDto Create( + Guid? libraryId = null, + string? path = null, + Guid? musicBrainzRecordingId = null, + string? isrc = null, + string? title = null, + string? artistName = null, + string? releaseName = null, + int? trackNumber = null, + int? durationInSeconds = null, + Guid? musicBrainzReleaseId = null, + int? discNumber = null, + Guid? musicBrainzWorkId = null, + string? workTitle = null) + { + return new TrackMetadataLookupDto( + libraryId ?? Guid.NewGuid(), + path ?? _faker.System.FilePath(), + musicBrainzRecordingId, + isrc, + title, + artistName, + releaseName, + trackNumber, + durationInSeconds, + musicBrainzReleaseId, + discNumber, + musicBrainzWorkId, + workTitle); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoFixture.cs index f6af707b..b9cfe9e0 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoFixture.cs @@ -27,6 +27,7 @@ public class BookMetadataLookupDtoFixture /// Optional. The title of the book. /// Optional. The author of the book. /// Optional. The language code of the book. + /// Whether the path should be included, or forced to . /// The created . public BookMetadataLookupDto Create( Guid? libraryId = null, @@ -35,11 +36,12 @@ public class BookMetadataLookupDtoFixture string? openLibraryId = null, string? title = null, string? author = null, - string? languageCode = null) + string? languageCode = null, + bool includePath = true) { return new BookMetadataLookupDto( libraryId ?? Guid.NewGuid(), - path ?? _faker.System.FilePath(), + includePath ? (path ?? _faker.System.FilePath()) : null!, isbn, openLibraryId, title, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/ChangePasswordRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/ChangePasswordRequestFixture.cs index 120b648d..3c96273b 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/ChangePasswordRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/ChangePasswordRequestFixture.cs @@ -23,19 +23,27 @@ public class ChangePasswordRequestFixture /// Optional. The current password. /// Optional. The new password. /// Optional. The new password confirmation. + /// Whether the username should be included, or forced to . + /// Whether the current password should be included, or forced to . + /// Whether the new password should be included, or forced to . + /// Whether the new password confirmation should be included, or forced to . /// The created . public ChangePasswordRequest Create( string? username = null, string? currentPassword = null, string? newPassword = null, - string? newPasswordConfirm = null) + string? newPasswordConfirm = null, + bool includeUsername = true, + bool includeCurrentPassword = true, + bool includeNewPassword = true, + bool includeNewPasswordConfirm = true) { string generatedNewPassword = newPassword ?? _faker.Internet.Password(); return new ChangePasswordRequest( - username ?? _faker.Internet.UserName(), - currentPassword ?? _faker.Internet.Password(), - generatedNewPassword, - newPasswordConfirm ?? generatedNewPassword + includeUsername ? (username ?? _faker.Internet.UserName()) : null, + includeCurrentPassword ? (currentPassword ?? _faker.Internet.Password()) : null, + includeNewPassword ? generatedNewPassword : null, + includeNewPasswordConfirm ? (newPasswordConfirm ?? generatedNewPassword) : null ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/LoginRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/LoginRequestFixture.cs index 77ffd8d7..a41a7575 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/LoginRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/LoginRequestFixture.cs @@ -22,16 +22,22 @@ public class LoginRequestFixture /// Optional. The username for login. /// Optional. The password for login. /// Optional. The TOTP code for two-factor authentication. + /// Whether the username should be included, or forced to . + /// Whether the password should be included, or forced to . + /// Whether the TOTP code should be included, or forced to . /// The created . public LoginRequest Create( string? username = null, string? password = null, - string? totpCode = null) + string? totpCode = null, + bool includeUsername = true, + bool includePassword = true, + bool includeTotpCode = true) { return new LoginRequest( - username ?? _faker.Internet.UserName(), - password ?? _faker.Internet.Password(), - totpCode ?? _faker.Random.Number(100000, 999999).ToString() + includeUsername ? (username ?? _faker.Internet.UserName()) : null, + includePassword ? (password ?? _faker.Internet.Password()) : null, + includeTotpCode ? (totpCode ?? _faker.Random.Number(100000, 999999).ToString()) : null ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RecoverPasswordRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RecoverPasswordRequestFixture.cs index 1e0a8fac..2c49bc5f 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RecoverPasswordRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RecoverPasswordRequestFixture.cs @@ -21,14 +21,18 @@ public class RecoverPasswordRequestFixture /// /// Optional. The username for password recovery. /// Optional. The TOTP code for verification. + /// Whether the username should be included, or forced to . + /// Whether the TOTP code should be included, or forced to . /// The created . public RecoverPasswordRequest Create( string? username = null, - string? totpCode = null) + string? totpCode = null, + bool includeUsername = true, + bool includeTotpCode = true) { return new RecoverPasswordRequest( - username ?? _faker.Internet.UserName(), - totpCode ?? _faker.Random.Number(100000, 999999).ToString() + includeUsername ? (username ?? _faker.Internet.UserName()) : null, + includeTotpCode ? (totpCode ?? _faker.Random.Number(100000, 999999).ToString()) : null ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RegistrationRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RegistrationRequestFixture.cs index d0a620ff..224321f9 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RegistrationRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RegistrationRequestFixture.cs @@ -23,18 +23,24 @@ public class RegistrationRequestFixture /// Optional. The password for registration. /// Optional. The password confirmation. /// Optional. Whether to use two-factor authentication. + /// Whether the username should be included, or forced to . + /// Whether the password should be included, or forced to . + /// Whether the password confirmation should be included, or forced to . /// The created . public RegistrationRequest Create( string? username = null, string? password = null, string? passwordConfirm = null, - bool? use2fa = null) + bool? use2fa = null, + bool includeUsername = true, + bool includePassword = true, + bool includePasswordConfirm = true) { string generatedPassword = password ?? _faker.Internet.Password(); return new RegistrationRequest( - username ?? _faker.Internet.UserName(), - generatedPassword, - passwordConfirm ?? generatedPassword, + includeUsername ? (username ?? _faker.Internet.UserName()) : null, + includePassword ? generatedPassword : null, + includePasswordConfirm ? (passwordConfirm ?? generatedPassword) : null, use2fa ?? _faker.Random.Bool() ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs index a28b3057..d59639d4 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs @@ -22,12 +22,14 @@ public class AddRoleRequestFixture /// /// Optional. The name of the role. /// Optional. The Ids of the permissions granted to the role. + /// Whether the permissions should be included, or forced to . /// The created . public AddRoleRequest Create( string? roleName = null, - List? permissions = null) + List? permissions = null, + bool includePermissions = true) { - return new AddRoleRequest(roleName ?? _faker.Commerce.Department(), permissions ?? []); + return new AddRoleRequest(roleName ?? _faker.Commerce.Department(), includePermissions ? (permissions ?? []) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs index 820d3494..eab6df4e 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs @@ -21,11 +21,13 @@ public class DeleteRoleRequestFixture /// Creates a random valid . /// /// Optional. The Id of the role to delete. + /// Whether the role Id should be included, or forced to . /// The created . public DeleteRoleRequest Create( - Guid? roleId = null) + Guid? roleId = null, + bool includeRoleId = true) { - return new DeleteRoleRequest(roleId ?? Guid.NewGuid()); + return new DeleteRoleRequest(includeRoleId ? (roleId ?? Guid.NewGuid()) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetAuthorizationRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetAuthorizationRequestFixture.cs index e1565547..a0027e97 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetAuthorizationRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetAuthorizationRequestFixture.cs @@ -18,11 +18,12 @@ public class GetAuthorizationRequestFixture /// Creates a with default or specified values. /// /// Optional. The user Id to use. + /// Whether the user Id should be included, or forced to . /// The created . - public GetAuthorizationRequest Create(Guid? userId = null) + public GetAuthorizationRequest Create(Guid? userId = null, bool includeUserId = true) { return new GetAuthorizationRequest( - UserId: userId ?? Guid.NewGuid() + UserId: includeUserId ? (userId ?? Guid.NewGuid()) : null ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs index 7d597f77..35b8c60b 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs @@ -18,11 +18,13 @@ public class GetUserPermissionsRequestFixture /// Creates a random valid . /// /// Optional. The Id of the user whose permissions are retrieved. + /// Whether the user Id should be included, or forced to . /// The created . public GetUserPermissionsRequest Create( - Guid? userId = null) + Guid? userId = null, + bool includeUserId = true) { - return new GetUserPermissionsRequest(userId ?? Guid.NewGuid()); + return new GetUserPermissionsRequest(includeUserId ? (userId ?? Guid.NewGuid()) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs index aa32e308..e415d613 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs @@ -18,11 +18,13 @@ public class GetUserRoleRequestFixture /// Creates a random valid . /// /// Optional. The Id of the user whose role is retrieved. + /// Whether the user Id should be included, or forced to . /// The created . public GetUserRoleRequest Create( - Guid? userId = null) + Guid? userId = null, + bool includeUserId = true) { - return new GetUserRoleRequest(userId ?? Guid.NewGuid()); + return new GetUserRoleRequest(includeUserId ? (userId ?? Guid.NewGuid()) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs index 893bb75c..cc9b908c 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs @@ -23,15 +23,17 @@ public class UpdateUserRoleAndPermissionsRequestFixture /// Optional. The Id of the user whose role and permissions are updated. /// Optional. The Id of the role assigned to the user. /// Optional. The Ids of the permissions assigned to the user. + /// Whether the role Id should be included, or forced to . /// The created . public UpdateUserRoleAndPermissionsRequest Create( Guid? userId = null, Guid? roleId = null, - List? permissions = null) + List? permissions = null, + bool includeRoleId = true) { return new UpdateUserRoleAndPermissionsRequest( userId ?? Guid.NewGuid(), - roleId ?? Guid.NewGuid(), + includeRoleId ? (roleId ?? Guid.NewGuid()) : null, permissions ?? [Guid.NewGuid(), Guid.NewGuid()] ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestFixture.cs index 2c5f4520..ffb49b7b 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestFixture.cs @@ -25,7 +25,7 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.Musi public class AddAlbumRequestFixture { private readonly Faker _faker = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly AddTrackRequestFixture _addTrackRequestFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); @@ -35,8 +35,11 @@ public class AddAlbumRequestFixture /// /// Optional. The album metadata of the album. /// Optional. The physical or digital medium of the album. + /// Optional. The outermost physical packaging of the album. /// Optional. The barcode of the album. /// Optional. The catalog number of the album. + /// Optional. The name of the label that issued the album. + /// Optional. The ASIN of the album. /// Optional. The MusicBrainz identifier of the release. /// Optional. The MusicBrainz identifier of the release group. /// Optional. The MusicBrainz identifier of the release artist. @@ -48,17 +51,23 @@ public class AddAlbumRequestFixture /// Whether the ratings list should be included, or forced to . /// Whether the tracks list should be included, or forced to . /// Whether the media format should be included, or forced to . + /// Whether the packaging should be included, or forced to . /// Whether the barcode should be included, or forced to . - /// Whether the catalog number should be included, or forced to . + /// Whether the catalog number should be included, or forced to . + /// Whether the label should be included, or forced to . + /// Whether the ASIN should be included, or forced to . /// Whether the MusicBrainz release Id should be included, or forced to . /// Whether the MusicBrainz release group Id should be included, or forced to . /// Whether the MusicBrainz release artist Id should be included, or forced to . /// The created request to add an album. public AddAlbumRequest Create( - AlbumMetadataDto? metadata = null, + MusicAlbumMetadataDto? metadata = null, MusicMediaFormat? mediaFormat = null, + MusicReleasePackaging? packaging = null, string? barcode = null, - string? catalogNumber = null, + List? catalogNumbers = null, + string? label = null, + string? asin = null, Guid? musicBrainzReleaseId = null, Guid? musicBrainzReleaseGroupId = null, Guid? musicBrainzReleaseArtistId = null, @@ -70,17 +79,23 @@ public class AddAlbumRequestFixture bool includeRatings = true, bool includeTracks = true, bool includeMediaFormat = true, + bool includePackaging = true, bool includeBarcode = true, - bool includeCatalogNumber = true, + bool includeCatalogNumbers = true, + bool includeLabel = true, + bool includeAsin = true, bool includeMusicBrainzReleaseId = true, bool includeMusicBrainzReleaseGroupId = true, bool includeMusicBrainzReleaseArtistId = true) { return new AddAlbumRequest( - includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMetadata ? (metadata ?? _musicAlbumMetadataDtoFixture.Create()) : null, includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includePackaging ? (packaging ?? _faker.PickRandom()) : null, includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, - includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null, + includeCatalogNumbers ? (catalogNumbers ?? [_faker.Random.AlphaNumeric(10)]) : null, + includeLabel ? (label ?? _faker.Company.CompanyName()) : null, + includeAsin ? (asin ?? _faker.Random.AlphaNumeric(10)) : null, includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs index cbf07c50..62e7fdf2 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs @@ -23,7 +23,7 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.Musi public class UpdateAlbumRequestFixture { private readonly Faker _faker = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); @@ -32,8 +32,11 @@ public class UpdateAlbumRequestFixture /// /// Optional. The album metadata of the album. /// Optional. The physical or digital medium of the album. + /// Optional. The outermost physical packaging of the album. /// Optional. The barcode of the album. /// Optional. The catalog number of the album. + /// Optional. The name of the label that issued the album. + /// Optional. The ASIN of the album. /// Optional. The MusicBrainz identifier of the release. /// Optional. The MusicBrainz identifier of the release group. /// Optional. The MusicBrainz identifier of the release artist. @@ -43,17 +46,23 @@ public class UpdateAlbumRequestFixture /// Whether the contributors list should be included, or forced to . /// Whether the ratings list should be included, or forced to . /// Whether the media format should be included, or forced to . + /// Whether the packaging should be included, or forced to . /// Whether the barcode should be included, or forced to . - /// Whether the catalog number should be included, or forced to . + /// Whether the catalog number should be included, or forced to . + /// Whether the label should be included, or forced to . + /// Whether the ASIN should be included, or forced to . /// Whether the MusicBrainz release Id should be included, or forced to . /// Whether the MusicBrainz release group Id should be included, or forced to . /// Whether the MusicBrainz release artist Id should be included, or forced to . /// The created request to update an album. public UpdateAlbumRequest Create( - AlbumMetadataDto? metadata = null, + MusicAlbumMetadataDto? metadata = null, MusicMediaFormat? mediaFormat = null, + MusicReleasePackaging? packaging = null, string? barcode = null, - string? catalogNumber = null, + List? catalogNumbers = null, + string? label = null, + string? asin = null, Guid? musicBrainzReleaseId = null, Guid? musicBrainzReleaseGroupId = null, Guid? musicBrainzReleaseArtistId = null, @@ -63,17 +72,23 @@ public class UpdateAlbumRequestFixture bool includeContributors = true, bool includeRatings = true, bool includeMediaFormat = true, + bool includePackaging = true, bool includeBarcode = true, - bool includeCatalogNumber = true, + bool includeCatalogNumbers = true, + bool includeLabel = true, + bool includeAsin = true, bool includeMusicBrainzReleaseId = true, bool includeMusicBrainzReleaseGroupId = true, bool includeMusicBrainzReleaseArtistId = true) { return new UpdateAlbumRequest( - includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMetadata ? (metadata ?? _musicAlbumMetadataDtoFixture.Create()) : null, includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includePackaging ? (packaging ?? _faker.PickRandom()) : null, includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, - includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null, + includeCatalogNumbers ? (catalogNumbers ?? [_faker.Random.AlphaNumeric(10)]) : null, + includeLabel ? (label ?? _faker.Company.CompanyName()) : null, + includeAsin ? (asin ?? _faker.Random.AlphaNumeric(10)) : null, includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs index df2aa7a4..c62670b9 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs @@ -1,7 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; @@ -20,40 +24,57 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.Musi public class AddArtistRequestFixture { private readonly Faker _faker = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); /// /// Creates a random valid request to add an artist. /// - /// Optional. The name of the artist. + /// Optional. The metadata of the artist. /// Optional. The website of the artist. /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The ISNI codes of the artist. /// Optional. The media contributors that make up the artist. + /// Optional. The ratings of the artist. /// Optional. The albums of the artist. - /// Whether the name should be included, or forced to . + /// Whether the metadata should be included, or forced to . /// Whether the website should be included, or forced to . /// Whether the MusicBrainz artist Id should be included, or forced to . + /// Whether the IPI codes should be included, or forced to . + /// Whether the ISNI codes should be included, or forced to . /// Whether the contributors list should be included, or forced to . + /// Whether the ratings list should be included, or forced to . /// Whether the albums list should be included, or forced to . /// The created request to add an artist. public AddArtistRequest Create( - string? name = null, + MusicArtistMetadataDto? metadata = null, string? website = null, Guid? musicBrainzArtistId = null, + List? ipis = null, + List? isnis = null, List? contributors = null, + List? ratings = null, List? albums = null, - bool includeName = true, + bool includeMetadata = true, bool includeWebsite = true, bool includeMusicBrainzArtistId = true, + bool includeIpis = true, + bool includeIsnis = true, bool includeContributors = true, + bool includeRatings = true, bool includeAlbums = true) { return new AddArtistRequest( - includeName ? (name ?? _faker.Name.FullName()) : null, + includeMetadata ? (metadata ?? _musicArtistMetadataDtoFixture.Create()) : null, includeWebsite ? (website ?? _faker.Internet.Url()) : null, includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeIpis ? (ipis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(9))]) : null, + includeIsnis ? (isnis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(16))]) : null, includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, includeAlbums ? (albums ?? _addAlbumRequestFixture.CreateMany(_faker.Random.Int(1, 3))) : null); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs index 89389dba..7da9e9b7 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs @@ -6,7 +6,6 @@ using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; @@ -24,7 +23,7 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.Musi public class UpdateArtistAlbumRequestFixture { private readonly Faker _faker = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly UpdateArtistTrackRequestFixture _updateArtistTrackRequestFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); @@ -35,8 +34,11 @@ public class UpdateArtistAlbumRequestFixture /// Optional. The Id of the album, when the album already exists. /// Optional. The album metadata of the album. /// Optional. The physical or digital medium of the album. + /// Optional. The outermost physical packaging of the album. /// Optional. The barcode of the album. /// Optional. The catalog number of the album. + /// Optional. The name of the label that issued the album. + /// Optional. The ASIN of the album. /// Optional. The MusicBrainz identifier of the release. /// Optional. The MusicBrainz identifier of the release group. /// Optional. The MusicBrainz identifier of the release artist. @@ -46,8 +48,11 @@ public class UpdateArtistAlbumRequestFixture /// Whether the album Id should be included, or forced to . /// Whether the metadata should be included, or forced to . /// Whether the media format should be included, or forced to . + /// Whether the packaging should be included, or forced to . /// Whether the barcode should be included, or forced to . - /// Whether the catalog number should be included, or forced to . + /// Whether the catalog number should be included, or forced to . + /// Whether the label should be included, or forced to . + /// Whether the ASIN should be included, or forced to . /// Whether the MusicBrainz release Id should be included, or forced to . /// Whether the MusicBrainz release group Id should be included, or forced to . /// Whether the MusicBrainz release artist Id should be included, or forced to . @@ -57,10 +62,13 @@ public class UpdateArtistAlbumRequestFixture /// The created request to update an album of an artist. public UpdateArtistAlbumRequest Create( Guid? albumId = null, - AlbumMetadataDto? metadata = null, + MusicAlbumMetadataDto? metadata = null, MusicMediaFormat? mediaFormat = null, + MusicReleasePackaging? packaging = null, string? barcode = null, - string? catalogNumber = null, + List? catalogNumbers = null, + string? label = null, + string? asin = null, Guid? musicBrainzReleaseId = null, Guid? musicBrainzReleaseGroupId = null, Guid? musicBrainzReleaseArtistId = null, @@ -70,8 +78,11 @@ public class UpdateArtistAlbumRequestFixture bool includeAlbumId = true, bool includeMetadata = true, bool includeMediaFormat = true, + bool includePackaging = true, bool includeBarcode = true, - bool includeCatalogNumber = true, + bool includeCatalogNumbers = true, + bool includeLabel = true, + bool includeAsin = true, bool includeMusicBrainzReleaseId = true, bool includeMusicBrainzReleaseGroupId = true, bool includeMusicBrainzReleaseArtistId = true, @@ -81,10 +92,13 @@ public class UpdateArtistAlbumRequestFixture { return new UpdateArtistAlbumRequest( includeAlbumId ? (albumId ?? _faker.Random.Guid()) : null, - includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMetadata ? (metadata ?? _musicAlbumMetadataDtoFixture.Create()) : null, includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includePackaging ? (packaging ?? _faker.PickRandom()) : null, includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, - includeCatalogNumber ? (catalogNumber ?? _faker.Random.String2(_faker.Random.Number(1, 50))) : null, + includeCatalogNumbers ? (catalogNumbers ?? [_faker.Random.String2(_faker.Random.Number(1, 50))]) : null, + includeLabel ? (label ?? _faker.Company.CompanyName()) : null, + includeAsin ? (asin ?? _faker.Random.AlphaNumeric(10)) : null, includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs index 111a76e0..356be292 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs @@ -1,7 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using System; using System.Collections.Generic; @@ -18,40 +22,57 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.Musi public class UpdateArtistRequestFixture { private readonly Faker _faker = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); /// /// Creates a random valid request to update an artist. /// - /// Optional. The name of the artist. + /// Optional. The metadata of the artist. /// Optional. The website of the artist. /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The ISNI codes of the artist. /// Optional. The media contributors that make up the artist. + /// Optional. The ratings of the artist. /// Optional. The albums of the artist. - /// Whether the name should be included, or forced to . + /// Whether the metadata should be included, or forced to . /// Whether the website should be included, or forced to . /// Whether the MusicBrainz artist Id should be included, or forced to . + /// Whether the IPI codes should be included, or forced to . + /// Whether the ISNI codes should be included, or forced to . /// Whether the contributors list should be included, or forced to . + /// Whether the ratings list should be included, or forced to . /// Whether the albums list should be included, or forced to . /// The created request to update an artist. public UpdateArtistRequest Create( - string? name = null, + MusicArtistMetadataDto? metadata = null, string? website = null, Guid? musicBrainzArtistId = null, + List? ipis = null, + List? isnis = null, List? contributors = null, + List? ratings = null, List? albums = null, - bool includeName = true, + bool includeMetadata = true, bool includeWebsite = true, bool includeMusicBrainzArtistId = true, + bool includeIpis = true, + bool includeIsnis = true, bool includeContributors = true, + bool includeRatings = true, bool includeAlbums = true) { return new UpdateArtistRequest( - includeName ? (name ?? _faker.Name.FullName()) : null, + includeMetadata ? (metadata ?? _musicArtistMetadataDtoFixture.Create()) : null, includeWebsite ? (website ?? _faker.Internet.Url()) : null, includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeIpis ? (ipis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(9))]) : null, + includeIsnis ? (isnis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(16))]) : null, includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, includeAlbums ? (albums ?? _updateArtistAlbumRequestFixture.CreateMany(_faker.Random.Int(1, 3))) : null); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs index 660c83c9..35f39975 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs @@ -26,7 +26,8 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.Musi public class UpdateArtistTrackRequestFixture { private readonly Faker _faker = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly MoodDtoFixture _moodDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -43,10 +44,9 @@ public class UpdateArtistTrackRequestFixture /// Optional. The script used by the language of the track. /// Optional. The musical key of the track. /// Optional. The tempo of the track in beats per minute. - /// Optional. The title of the work the track is a recording of. + /// Optional. The work the track is a recording of. /// Optional. The MusicBrainz identifier of the recording. /// Optional. The MusicBrainz identifier of the track. - /// Optional. The MusicBrainz identifier of the work. /// Optional. The moods of the track. /// Optional. The ISRC codes of the track. /// Optional. The media contributors that performed on the track. @@ -62,7 +62,6 @@ public class UpdateArtistTrackRequestFixture /// Whether the work should be included, or forced to . /// Whether the MusicBrainz recording Id should be included, or forced to . /// Whether the MusicBrainz track Id should be included, or forced to . - /// Whether the MusicBrainz work Id should be included, or forced to . /// Whether the moods should be included, or forced to . /// Whether the ISRC codes should be included, or forced to . /// Whether the contributors list should be included, or forced to . @@ -71,16 +70,15 @@ public class UpdateArtistTrackRequestFixture public UpdateArtistTrackRequest Create( Guid? trackId = null, string? path = null, - AudioMetadataDto? metadata = null, + MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, string? script = null, MusicKey? key = null, int? bpm = null, - string? work = null, + MusicWorkDto? work = null, Guid? musicBrainzRecordingId = null, Guid? musicBrainzTrackId = null, - Guid? musicBrainzWorkId = null, List? moods = null, List? isrcs = null, List? contributors = null, @@ -96,7 +94,6 @@ public class UpdateArtistTrackRequestFixture bool includeWork = true, bool includeMusicBrainzRecordingId = true, bool includeMusicBrainzTrackId = true, - bool includeMusicBrainzWorkId = true, bool includeMoods = true, bool includeIsrcs = true, bool includeContributors = true, @@ -105,16 +102,15 @@ public class UpdateArtistTrackRequestFixture return new UpdateArtistTrackRequest( includeTrackId ? (trackId ?? _faker.Random.Guid()) : null, includePath ? (path ?? Path.Combine(Path.GetTempPath(), "lumina-tracks", _faker.System.FileName())) : null, - includeMetadata ? (metadata ?? _audioMetadataDtoFixture.Create()) : null, + includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null, includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 30)) : null, includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null, includeScript ? (script ?? _faker.Random.AlphaNumeric(4)) : null, includeKey ? (key ?? _faker.PickRandom()) : null, includeBpm ? (bpm ?? _faker.Random.Int(40, 220)) : null, - includeWork ? (work ?? _faker.Lorem.Sentence()) : null, + includeWork ? (work ?? _musicWorkDtoFixture.Create()) : null, includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null, includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null, - includeMusicBrainzWorkId ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null, includeMoods ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, includeIsrcs ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestFixture.cs index c45bcafb..c832d920 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestFixture.cs @@ -26,7 +26,8 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.Musi public class AddTrackRequestFixture { private readonly Faker _faker = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly MoodDtoFixture _moodDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -42,10 +43,9 @@ public class AddTrackRequestFixture /// Optional. The script used by the language of the track. /// Optional. The musical key of the track. /// Optional. The tempo of the track in beats per minute. - /// Optional. The title of the work the track is a recording of. + /// Optional. The work the track is a recording of. /// Optional. The MusicBrainz identifier of the recording. /// Optional. The MusicBrainz identifier of the track. - /// Optional. The MusicBrainz identifier of the work. /// Optional. The list of moods of the track. /// Optional. The list of ISRC of the track. /// Optional. The list of media contributors that performed on the track. @@ -60,7 +60,6 @@ public class AddTrackRequestFixture /// Whether the work should be included, or forced to . /// Whether the MusicBrainz recording Id should be included, or forced to . /// Whether the MusicBrainz track Id should be included, or forced to . - /// Whether the MusicBrainz work Id should be included, or forced to . /// Whether the moods should be included, or forced to . /// Whether the ISRC codes should be included, or forced to . /// Whether the contributors should be included, or forced to . @@ -68,16 +67,15 @@ public class AddTrackRequestFixture /// The created request to add a track. public AddTrackRequest Create( string? path = null, - AudioMetadataDto? metadata = null, + MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, string? script = null, MusicKey? key = null, int? bpm = null, - string? work = null, + MusicWorkDto? work = null, Guid? musicBrainzRecordingId = null, Guid? musicBrainzTrackId = null, - Guid? musicBrainzWorkId = null, List? moods = null, List? isrcs = null, List? contributors = null, @@ -92,7 +90,6 @@ public class AddTrackRequestFixture bool includeWork = true, bool includeMusicBrainzRecordingId = true, bool includeMusicBrainzTrackId = true, - bool includeMusicBrainzWorkId = true, bool includeMoods = true, bool includeIsrcs = true, bool includeContributors = true, @@ -100,16 +97,15 @@ public class AddTrackRequestFixture { return new AddTrackRequest( includePath ? path ?? Path.Combine(Path.GetTempPath(), "lumina-tracks", _faker.System.FileName()) : null, - includeMetadata ? metadata ?? _audioMetadataDtoFixture.Create() : null, + includeMetadata ? metadata ?? _musicTrackMetadataDtoFixture.Create() : null, includeTrackNumber ? trackNumber ?? _faker.Random.Int(1, 30) : null, includeDiscNumber ? discNumber ?? _faker.Random.Int(1, 3) : null, includeScript ? script ?? _faker.Random.AlphaNumeric(4) : null, includeKey ? key ?? _faker.PickRandom() : null, includeBpm ? bpm ?? _faker.Random.Int(40, 220) : null, - includeWork ? work ?? _faker.Lorem.Sentence() : null, + includeWork ? work ?? _musicWorkDtoFixture.Create() : null, includeMusicBrainzRecordingId ? musicBrainzRecordingId ?? _faker.Random.Guid() : null, includeMusicBrainzTrackId ? musicBrainzTrackId ?? _faker.Random.Guid() : null, - includeMusicBrainzWorkId ? musicBrainzWorkId ?? _faker.Random.Guid() : null, includeMoods ? moods ?? _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null, includeIsrcs ? isrcs ?? _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null, includeContributors ? contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs index f73927dd..bdf7e052 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs @@ -25,7 +25,8 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.Musi public class UpdateTrackRequestFixture { private readonly Faker _faker = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly MoodDtoFixture _moodDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -41,10 +42,9 @@ public class UpdateTrackRequestFixture /// Optional. The script used by the language of the track. /// Optional. The musical key of the track. /// Optional. The tempo of the track in beats per minute. - /// Optional. The title of the work the track is a recording of. + /// Optional. The work the track is a recording of. /// Optional. The MusicBrainz identifier of the recording. /// Optional. The MusicBrainz identifier of the track. - /// Optional. The MusicBrainz identifier of the work. /// Optional. The moods of the track. /// Optional. The ISRC codes of the track. /// Optional. The media contributors that performed on the track. @@ -56,7 +56,6 @@ public class UpdateTrackRequestFixture /// Whether the work should be included, or forced to . /// Whether the MusicBrainz recording Id should be included, or forced to . /// Whether the MusicBrainz track Id should be included, or forced to . - /// Whether the MusicBrainz work Id should be included, or forced to . /// Whether the moods should be included, or forced to . /// Whether the ISRC codes should be included, or forced to . /// Whether the contributors list should be included, or forced to . @@ -67,16 +66,15 @@ public class UpdateTrackRequestFixture /// The created request to update a track. public UpdateTrackRequest Create( string? path = null, - AudioMetadataDto? metadata = null, + MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, string? script = null, MusicKey? key = null, int? bpm = null, - string? work = null, + MusicWorkDto? work = null, Guid? musicBrainzRecordingId = null, Guid? musicBrainzTrackId = null, - Guid? musicBrainzWorkId = null, List? moods = null, List? isrcs = null, List? contributors = null, @@ -88,7 +86,6 @@ public class UpdateTrackRequestFixture bool includeWork = true, bool includeMusicBrainzRecordingId = true, bool includeMusicBrainzTrackId = true, - bool includeMusicBrainzWorkId = true, bool includeMoods = true, bool includeIsrcs = true, bool includeContributors = true, @@ -99,16 +96,15 @@ public class UpdateTrackRequestFixture { return new UpdateTrackRequest( includePath ? (path ?? _faker.System.FilePath()) : null, - includeMetadata ? (metadata ?? _audioMetadataDtoFixture.Create()) : null, + includeMetadata ? (metadata ?? _musicTrackMetadataDtoFixture.Create()) : null, includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 20)) : null, includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null, includeScript ? (script ?? _faker.Random.String2(_faker.Random.Number(1, 50))) : null, includeKey ? (key ?? _faker.PickRandom()) : null, includeBpm ? (bpm ?? _faker.Random.Int(40, 240)) : null, - includeWork ? (work ?? _faker.Music.Genre()) : null, + includeWork ? (work ?? _musicWorkDtoFixture.Create()) : null, includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null, includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null, - includeMusicBrainzWorkId ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null, includeMoods ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, includeIsrcs ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs index b48be3f2..f48ad45d 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs @@ -28,6 +28,7 @@ public class AddLibraryRequestFixture /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. + /// Optional. The ordered parts of the path template of the media library. /// The created . public AddLibraryRequest Create( string? title = null, @@ -38,7 +39,8 @@ public class AddLibraryRequestFixture bool? isLocked = null, bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, - bool? shouldSkipUnchangedDirectoriesDuringScan = null) + bool? shouldSkipUnchangedDirectoriesDuringScan = null, + LibraryPathTemplatePartRequest[]? pathTemplateParts = null) { return new AddLibraryRequest( title ?? _faker.Commerce.Department(), @@ -49,7 +51,8 @@ public class AddLibraryRequestFixture isLocked ?? _faker.Random.Bool(), canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), - shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool() + shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), + pathTemplateParts ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestFixture.cs new file mode 100644 index 00000000..d8e865c3 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available path parts are retrieved. + /// The created . + public GetLibraryPathTemplatePartsRequest Create(string? libraryType = null) + { + return new GetLibraryPathTemplatePartsRequest(libraryType ?? "Music"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequestFixture.cs new file mode 100644 index 00000000..caa489ed --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequestFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathTemplatePartRequest Create( + string? kind = null, + string? representation = null, + bool isOptional = false) + { + return new LibraryPathTemplatePartRequest( + kind ?? "Artist", + representation ?? "{0}", + isOptional); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs index ca1bd352..782f337b 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs @@ -31,6 +31,7 @@ public class UpdateLibraryRequestFixture /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. + /// Optional. The ordered parts of the path template of the media library. /// The created . public UpdateLibraryRequest Create( Guid? id = null, @@ -43,7 +44,8 @@ public class UpdateLibraryRequestFixture bool? isLocked = null, bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, - bool? shouldSkipUnchangedDirectoriesDuringScan = null) + bool? shouldSkipUnchangedDirectoriesDuringScan = null, + LibraryPathTemplatePartRequest[]? pathTemplateParts = null) { return new UpdateLibraryRequest( id ?? _faker.Random.Guid(), @@ -56,7 +58,8 @@ public class UpdateLibraryRequestFixture isLocked ?? _faker.Random.Bool(), canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), - shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool() + shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), + pathTemplateParts ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs index 921c81d1..1219ed0a 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs @@ -22,17 +22,21 @@ public class UpdatePluginSettingsRequestFixture /// /// Optional. The Id of the plugin whose settings are updated. /// Optional. The settings to apply to the plugin. + /// Whether the settings should be included, or forced to . /// The created . public UpdatePluginSettingsRequest Create( Guid? pluginId = null, - IReadOnlyDictionary? settings = null) + IReadOnlyDictionary? settings = null, + bool includeSettings = true) { return new UpdatePluginSettingsRequest( pluginId ?? _faker.Random.Guid(), - settings ?? new Dictionary - { - [_faker.Lorem.Word()] = _faker.Lorem.Word() - } + includeSettings + ? settings ?? new Dictionary + { + [_faker.Lorem.Word()] = _faker.Lorem.Word() + } + : null ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/DeleteThemeRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/DeleteThemeRequestFixture.cs index 4034dfff..7e11413f 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/DeleteThemeRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/DeleteThemeRequestFixture.cs @@ -20,10 +20,11 @@ public class DeleteThemeRequestFixture /// Creates a random valid . /// /// Optional. The manifest id of the theme to delete. + /// Whether the theme Id should be included, or forced to . /// The created . - public DeleteThemeRequest Create(string? themeId = null) + public DeleteThemeRequest Create(string? themeId = null, bool includeThemeId = true) { - return new DeleteThemeRequest(themeId ?? _faker.Lorem.Slug(2)); + return new DeleteThemeRequest(includeThemeId ? (themeId ?? _faker.Lorem.Slug(2)) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeArchiveRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeArchiveRequestFixture.cs index a7421ee3..abbde935 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeArchiveRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeArchiveRequestFixture.cs @@ -20,10 +20,11 @@ public class GetThemeArchiveRequestFixture /// Creates a random valid . /// /// Optional. The manifest id of the theme. + /// Whether the theme Id should be included, or forced to . /// The created . - public GetThemeArchiveRequest Create(string? themeId = null) + public GetThemeArchiveRequest Create(string? themeId = null, bool includeThemeId = true) { - return new GetThemeArchiveRequest(themeId ?? _faker.Lorem.Slug(2)); + return new GetThemeArchiveRequest(includeThemeId ? (themeId ?? _faker.Lorem.Slug(2)) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeAssetRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeAssetRequestFixture.cs index b78f5459..865dd787 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeAssetRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeAssetRequestFixture.cs @@ -21,12 +21,19 @@ public class GetThemeAssetRequestFixture /// /// Optional. The manifest id of the theme. /// Optional. The asset path relative to the theme pack root. + /// Whether the theme Id should be included, or forced to . + /// Whether the asset path should be included, or forced to . /// The created . - public GetThemeAssetRequest Create(string? themeId = null, string? assetPath = null) + public GetThemeAssetRequest Create( + string? themeId = null, + string? assetPath = null, + bool includeThemeId = true, + bool includeAssetPath = true) { return new GetThemeAssetRequest( - themeId ?? _faker.Lorem.Slug(2), - assetPath ?? _faker.System.FilePath()); + includeThemeId ? (themeId ?? _faker.Lorem.Slug(2)) : null, + includeAssetPath ? (assetPath ?? _faker.System.FilePath()) : null + ); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeTemplateRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeTemplateRequestFixture.cs index 1b9da5de..6c1b35ce 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeTemplateRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeTemplateRequestFixture.cs @@ -21,12 +21,19 @@ public class GetThemeTemplateRequestFixture /// /// Optional. The manifest id of the theme. /// Optional. The page key that selects the template. + /// Whether the theme Id should be included, or forced to . + /// Whether the page key should be included, or forced to . /// The created . - public GetThemeTemplateRequest Create(string? themeId = null, string? pageKey = null) + public GetThemeTemplateRequest Create( + string? themeId = null, + string? pageKey = null, + bool includeThemeId = true, + bool includePageKey = true) { return new GetThemeTemplateRequest( - themeId ?? _faker.Lorem.Slug(2), - pageKey ?? _faker.Lorem.Word()); + includeThemeId ? (themeId ?? _faker.Lorem.Slug(2)) : null, + includePageKey ? (pageKey ?? _faker.Lorem.Word()) : null + ); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/SetCurrentThemeRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/SetCurrentThemeRequestFixture.cs index 78d68248..64cb3c45 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/SetCurrentThemeRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/SetCurrentThemeRequestFixture.cs @@ -20,10 +20,11 @@ public class SetCurrentThemeRequestFixture /// Creates a random valid . /// /// Optional. The manifest id of the theme to activate. + /// Whether the theme Id should be included, or forced to . /// The created . - public SetCurrentThemeRequest Create(string? themeId = null) + public SetCurrentThemeRequest Create(string? themeId = null, bool includeThemeId = true) { - return new SetCurrentThemeRequest(themeId ?? _faker.Lorem.Slug(2)); + return new SetCurrentThemeRequest(includeThemeId ? (themeId ?? _faker.Lorem.Slug(2)) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs index 37f2fc05..6240d10e 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs @@ -24,6 +24,7 @@ public class UpdateUserSettingsRequestFixture /// Whether the "The" prefix is ignored by the alpha picker. /// Whether the theme data served to this user is cached. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. + /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Whether PDF books are rendered as page images for the user. /// Whether the styles of the book content are preserved when it is rendered for the user. /// The created . @@ -33,6 +34,7 @@ public class UpdateUserSettingsRequestFixture bool? shouldIgnoreThePrefixForAlphaPicker = null, bool? isThemeCachingEnabled = null, bool? shouldAggregateMetadataWhenMissing = null, + bool? shouldAggregateArtworkWhenMissing = null, bool? shouldRenderPdfAsImages = null, bool? shouldPreserveBookStyles = null) { @@ -42,6 +44,7 @@ public class UpdateUserSettingsRequestFixture shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(), isThemeCachingEnabled ?? _faker.Random.Bool(), shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool(), + shouldAggregateArtworkWhenMissing ?? _faker.Random.Bool(), shouldRenderPdfAsImages ?? _faker.Random.Bool(), shouldPreserveBookStyles ?? _faker.Random.Bool()); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Directories/DirectoryResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Directories/DirectoryResponseFixture.cs index 93239e65..3c25eb76 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Directories/DirectoryResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Directories/DirectoryResponseFixture.cs @@ -16,7 +16,7 @@ namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Director public class DirectoryResponseFixture { private readonly Faker _faker = new(); - private readonly FileSystemItemDtoFixture _fileSystemItemModelFixture = new(); + private readonly FileSystemItemDtoFixture _fileSystemItemDtoFixture = new(); /// /// Creates a random valid . @@ -30,7 +30,7 @@ public class DirectoryResponseFixture _faker.System.FileName(), _faker.Date.Past(), _faker.Date.Recent(), - _fileSystemItemModelFixture.CreateMany(itemCount) + _fileSystemItemDtoFixture.CreateMany(itemCount) ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs index 22ea8889..653ec988 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs @@ -25,7 +25,7 @@ namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.Mus public class AlbumResponseFixture { private readonly Faker _faker = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); private readonly TrackResponseFixture _trackResponseFixture = new(); @@ -38,8 +38,11 @@ public class AlbumResponseFixture /// Optional. The Id of the media library the album belongs to. /// Optional. The album metadata of the album. /// Optional. The physical or digital medium of the album. + /// Optional. The outermost physical packaging of the album. /// Optional. The barcode of the album. /// Optional. The catalog number of the album. + /// Optional. The name of the label that issued the album. + /// Optional. The ASIN of the album. /// Optional. The MusicBrainz identifier of the release. /// Optional. The MusicBrainz identifier of the release group. /// Optional. The MusicBrainz identifier of the release artist. @@ -49,8 +52,11 @@ public class AlbumResponseFixture /// Optional. The list of ratings of the album. /// Optional. The list of tracks of the album. /// Whether the media format should be included, or forced to . + /// Whether the packaging should be included, or forced to . /// Whether the barcode should be included, or forced to . - /// Whether the catalog number should be included, or forced to . + /// Whether the catalog number should be included, or forced to . + /// Whether the label should be included, or forced to . + /// Whether the ASIN should be included, or forced to . /// Whether the MusicBrainz release Id should be included, or forced to . /// Whether the MusicBrainz release group Id should be included, or forced to . /// Whether the MusicBrainz release artist Id should be included, or forced to . @@ -63,10 +69,13 @@ public class AlbumResponseFixture Guid? id = null, Guid? artistId = null, Guid? libraryId = null, - AlbumMetadataDto? metadata = null, + MusicAlbumMetadataDto? metadata = null, MusicMediaFormat? mediaFormat = null, + MusicReleasePackaging? packaging = null, string? barcode = null, - string? catalogNumber = null, + List? catalogNumbers = null, + string? label = null, + string? asin = null, Guid? musicBrainzReleaseId = null, Guid? musicBrainzReleaseGroupId = null, Guid? musicBrainzReleaseArtistId = null, @@ -76,8 +85,11 @@ public class AlbumResponseFixture List? ratings = null, List? tracks = null, bool includeMediaFormat = true, + bool includePackaging = true, bool includeBarcode = true, - bool includeCatalogNumber = true, + bool includeCatalogNumbers = true, + bool includeLabel = true, + bool includeAsin = true, bool includeMusicBrainzReleaseId = true, bool includeMusicBrainzReleaseGroupId = true, bool includeMusicBrainzReleaseArtistId = true, @@ -90,10 +102,13 @@ public class AlbumResponseFixture id ?? Guid.NewGuid(), artistId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid(), - metadata ?? _albumMetadataDtoFixture.Create(), + metadata ?? _musicAlbumMetadataDtoFixture.Create(), includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includePackaging ? (packaging ?? _faker.PickRandom()) : null, includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, - includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null, + includeCatalogNumbers ? (catalogNumbers ?? [_faker.Random.AlphaNumeric(10)]) : null, + includeLabel ? (label ?? _faker.Company.CompanyName()) : null, + includeAsin ? (asin ?? _faker.Random.AlphaNumeric(10)) : null, includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? Guid.NewGuid()) : null, includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? Guid.NewGuid()) : null, includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? Guid.NewGuid()) : null, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs index c8e4178b..f22f8359 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs @@ -1,7 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; @@ -20,7 +24,9 @@ namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.Mus public class ArtistResponseFixture { private readonly Faker _faker = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); private readonly AlbumResponseFixture _albumResponseFixture = new(); /// @@ -28,45 +34,60 @@ public class ArtistResponseFixture /// /// Optional. The Id of the artist. /// Optional. The Id of the media library the artist belongs to. - /// Optional. The name of the artist. + /// Optional. The metadata of the artist. /// Optional. The website of the artist. /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The ISNI codes of the artist. /// Optional. The list of contributor references of the artist. + /// Optional. The list of ratings of the artist. /// Optional. The list of albums of the artist. /// Optional. The date and time when the artist was created. /// Optional. The date and time when the artist was updated. /// Whether the website should be included, or forced to . /// Whether the MusicBrainz artist Id should be included, or forced to . + /// Whether the IPI codes should be included, or forced to . + /// Whether the ISNI codes should be included, or forced to . /// Whether the update date should be included, or forced to . /// Whether the contributors should be included, or forced to . + /// Whether the ratings should be included, or forced to . /// Whether the albums should be included, or forced to . /// The created . public ArtistResponse Create( Guid? id = null, Guid? libraryId = null, - string? name = null, + MusicArtistMetadataDto? metadata = null, string? website = null, Guid? musicBrainzArtistId = null, + List? ipis = null, + List? isnis = null, List? contributors = null, + List? ratings = null, List? albums = null, DateTime? createdOnUtc = null, DateTime? updatedOnUtc = null, bool includeWebsite = true, bool includeMusicBrainzArtistId = true, + bool includeIpis = true, + bool includeIsnis = true, bool includeUpdatedOnUtc = true, bool includeContributors = true, + bool includeRatings = true, bool includeAlbums = true) { return new ArtistResponse( id ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid(), - name ?? _faker.Name.FullName(), + metadata ?? _musicArtistMetadataDtoFixture.Create(), includeWebsite ? (website ?? _faker.Internet.Url()) : null, includeMusicBrainzArtistId ? (musicBrainzArtistId ?? Guid.NewGuid()) : null, - includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1)) : null, - includeAlbums ? (albums ?? _albumResponseFixture.CreateMany(1)) : null, + includeIpis ? (ipis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(9))]) : null, + includeIsnis ? (isnis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(16))]) : null, createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), - includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent().ToUniversalTime()) : null); + includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent().ToUniversalTime()) : null, + includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1)) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(1)) : null, + includeAlbums ? (albums ?? _albumResponseFixture.CreateMany(1)) : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs index 2c009ff5..b79eb390 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs @@ -25,7 +25,8 @@ namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.Mus public class TrackResponseFixture { private readonly Faker _faker = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly MoodDtoFixture _moodDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -44,10 +45,9 @@ public class TrackResponseFixture /// Optional. The script used by the language of the track. /// Optional. The musical key of the track. /// Optional. The tempo of the track in beats per minute. - /// Optional. The title of the work the track is a recording of. + /// Optional. The work the track is a recording of. /// Optional. The MusicBrainz recording Id of the track. /// Optional. The MusicBrainz track Id of the track. - /// Optional. The MusicBrainz work Id of the track. /// Optional. The date and time when the track was created. /// Optional. The date and time when the track was updated. /// Optional. The list of moods of the track. @@ -56,23 +56,21 @@ public class TrackResponseFixture /// Optional. The list of ratings of the track. /// Whether the MusicBrainz recording Id should be included, or forced to . /// Whether the MusicBrainz track Id should be included, or forced to . - /// Whether the MusicBrainz work Id should be included, or forced to . /// The created . public TrackResponse Create( Guid? id = null, Guid? albumId = null, Guid? libraryId = null, string? path = null, - AudioMetadataDto? metadata = null, + MusicTrackMetadataDto? metadata = null, int? trackNumber = null, int? discNumber = null, string? script = null, MusicKey? key = null, int? bpm = null, - string? work = null, + MusicWorkDto? work = null, Guid? musicBrainzRecordingId = null, Guid? musicBrainzTrackId = null, - Guid? musicBrainzWorkId = null, DateTime? createdOnUtc = null, DateTime? updatedOnUtc = null, List? moods = null, @@ -80,24 +78,22 @@ public class TrackResponseFixture List? contributors = null, List? ratings = null, bool includeMusicBrainzRecordingId = true, - bool includeMusicBrainzTrackId = true, - bool includeMusicBrainzWorkId = true) + bool includeMusicBrainzTrackId = true) { return new TrackResponse( id ?? Guid.NewGuid(), albumId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid(), path ?? _faker.System.FilePath(), - metadata ?? _audioMetadataDtoFixture.Create(), + metadata ?? _musicTrackMetadataDtoFixture.Create(), trackNumber ?? _faker.Random.Int(1, 30), discNumber ?? (_faker.Random.Bool() ? _faker.Random.Int(1, 3) : null), script ?? (_faker.Random.Bool() ? _faker.Random.AlphaNumeric(4) : null), key ?? (_faker.Random.Bool() ? _faker.PickRandom() : null), bpm ?? (_faker.Random.Bool() ? _faker.Random.Int(40, 220) : null), - work ?? (_faker.Random.Bool() ? _faker.Lorem.Sentence() : null), + work ?? _musicWorkDtoFixture.Create(), includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? Guid.NewGuid()) : null, includeMusicBrainzTrackId ? (musicBrainzTrackId ?? Guid.NewGuid()) : null, - includeMusicBrainzWorkId ? (musicBrainzWorkId ?? Guid.NewGuid()) : null, createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), updatedOnUtc ?? (_faker.Random.Bool() ? _faker.Date.Recent().ToUniversalTime() : null), moods ?? _moodDtoFixture.CreateMany(1), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponseFixture.cs new file mode 100644 index 00000000..7b486d2f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponseFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartDefinitionResponseFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The value type captured by the path part. + /// Optional. The default representation of the path part. + /// Whether the path part is optional by default. + /// The created . + public LibraryPathPartDefinitionResponse Create( + string? kind = null, + string? valueType = null, + string? defaultRepresentation = null, + bool isOptionalByDefault = false) + { + return new LibraryPathPartDefinitionResponse( + kind ?? "Artist", + valueType ?? "Text", + defaultRepresentation ?? "{0}", + isOptionalByDefault); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponseFixture.cs new file mode 100644 index 00000000..fb64c03b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponseFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateCatalogResponseFixture +{ + private readonly LibraryPathPartDefinitionResponseFixture _libraryPathPartDefinitionResponseFixture = new(); + private readonly LibraryPathTemplatePartResponseFixture _libraryPathTemplatePartResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The path parts that can be used in the path template of the library type. + /// Optional. The ordered parts of the default path template of the library type. + /// Whether the catalog should carry selectable path parts. When , no parts are created. + /// Whether the catalog should carry default template parts. When , no default template parts are created. + /// The created . + public LibraryPathTemplateCatalogResponse Create( + List? parts = null, + List? defaultTemplateParts = null, + bool includeParts = true, + bool includeDefaultTemplateParts = true) + { + return new LibraryPathTemplateCatalogResponse( + includeParts ? (parts ?? _libraryPathPartDefinitionResponseFixture.CreateMany(2)) : [], + includeDefaultTemplateParts ? (defaultTemplateParts ?? _libraryPathTemplatePartResponseFixture.CreateMany(2)) : []); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponseFixture.cs new file mode 100644 index 00000000..b68c49c3 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponseFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartResponseFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathTemplatePartResponse Create( + string? kind = null, + string? representation = null, + bool isOptional = false) + { + return new LibraryPathTemplatePartResponse( + kind ?? "Artist", + representation ?? "{0}", + isOptional); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs index 06493766..145e7748 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs @@ -32,6 +32,7 @@ public class LibraryResponseFixture /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. + /// Optional. The ordered parts of the path template of the media library. /// Optional. The date and time when the library was created. /// Optional. The date and time when the library was updated. /// The created . @@ -47,6 +48,7 @@ public class LibraryResponseFixture bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null, + List? pathTemplateParts = null, DateTime? createdOnUtc = null, DateTime? updatedOnUtc = null) { @@ -62,6 +64,7 @@ public class LibraryResponseFixture canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), + pathTemplateParts ?? [], createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), updatedOnUtc ); diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs index 7226bbf4..6c6f41e5 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs @@ -7,6 +7,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs index cd4d3fbd..0723a9d2 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs @@ -26,6 +26,7 @@ public class UserSettingsResponseFixture /// Optional. Whether the "The" prefix is ignored by the alpha picker. /// Optional. Whether the theme data served to this user is cached. /// Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. + /// Optional. Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Optional. Whether PDF books are rendered as page images for the user. /// Optional. Whether the styles of the book content are preserved when it is rendered for the user. /// The created . @@ -36,6 +37,7 @@ public class UserSettingsResponseFixture bool? shouldIgnoreThePrefixForAlphaPicker = null, bool? isThemeCachingEnabled = null, bool? shouldAggregateMetadataWhenMissing = null, + bool? shouldAggregateArtworkWhenMissing = null, bool? shouldRenderPdfAsImages = null, bool? shouldPreserveBookStyles = null) { @@ -46,6 +48,7 @@ public class UserSettingsResponseFixture shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(), isThemeCachingEnabled ?? _faker.Random.Bool(), shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool(), + shouldAggregateArtworkWhenMissing ?? _faker.Random.Bool(), shouldRenderPdfAsImages ?? _faker.Random.Bool(), shouldPreserveBookStyles ?? _faker.Random.Bool()); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Lumina.Contracts.Fixtures.csproj b/tests/Common/Lumina.Contracts.Fixtures/Lumina.Contracts.Fixtures.csproj index eba4f3dd..cef3e528 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Lumina.Contracts.Fixtures.csproj +++ b/tests/Common/Lumina.Contracts.Fixtures/Lumina.Contracts.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataFixture.cs index 3c3e41c1..f8c4be25 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataFixture.cs @@ -40,6 +40,11 @@ public class AudioMetadataFixture /// Optional. The bit depth of the audio. /// Optional. The audio codec used. /// Optional. The bitrate of the audio, in kbps. + /// Optional. The AcoustID fingerprint identifier of the audio file. + /// Optional. The ReplayGain track gain, in decibels. + /// Optional. The ReplayGain track peak. + /// Optional. The ReplayGain album gain, in decibels. + /// Optional. The ReplayGain album peak. /// The created . public AudioMetadata Create( string? title = null, @@ -55,7 +60,12 @@ public class AudioMetadataFixture Optional? originalLanguage = null, Optional? bitDepth = null, Optional? audioCodec = null, - Optional? bitrate = null) + Optional? bitrate = null, + Optional? acoustId = null, + Optional? replayGainTrackGain = null, + Optional? replayGainTrackPeak = null, + Optional? replayGainAlbumGain = null, + Optional? replayGainAlbumPeak = null) { return AudioMetadata.Create( title ?? _faker.Music.Genre(), @@ -71,7 +81,12 @@ public class AudioMetadataFixture originalLanguage ?? Optional.None(), bitDepth ?? Optional.Some(_faker.Random.Int(8, 32)), audioCodec ?? Optional.Some("PCM"), - bitrate ?? Optional.Some(_faker.Random.Int(128, 320))).Value; + bitrate ?? Optional.Some(_faker.Random.Int(128, 320)), + acoustId ?? Optional.None(), + replayGainTrackGain ?? Optional.None(), + replayGainTrackPeak ?? Optional.None(), + replayGainAlbumGain ?? Optional.None(), + replayGainAlbumPeak ?? Optional.None()).Value; } /// diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistFixture.cs index 5182b00c..d72a72af 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistFixture.cs @@ -1,13 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -22,35 +27,96 @@ namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext [ExcludeFromCodeCoverage] public class ArtistFixture { + private const int MINIMUM_LIFESPAN_YEAR = 1900; + private const int MAXIMUM_LIFESPAN_YEAR = 2026; + private readonly Faker _faker = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly AlbumFixture _albumFixture = new(); private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + private readonly MusicAreaFixture _musicAreaFixture = new(); + private readonly MusicArtistAliasFixture _musicArtistAliasFixture = new(); + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly AudioRatingFixture _audioRatingFixture = new(); /// /// Creates a random valid domain aggregate root. /// /// Optional. The Id of the media library this artist belongs to. /// Optional. The name of the artist. + /// Optional. The sort name of the artist. + /// Optional. The disambiguation comment of the artist. + /// Optional. The type of the artist. + /// Optional. The gender of the artist. + /// Optional. The country of the artist. + /// Optional. The area the artist is primarily identified with. + /// Optional. The area the artist began in. + /// Optional. The area the artist ended in. + /// Optional. The date the artist started existing. + /// Optional. The date the artist stopped existing. + /// Optional. Whether the artist no longer exists. /// Optional. The website of the artist. /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The ISNI codes of the artist. + /// Optional. The alternative names of the artist. + /// Optional. The genres associated with the artist. + /// Optional. The tags associated with the artist. + /// Optional. The ratings of the artist. /// Optional. The media contributors that make up the artist. /// Optional. The albums of the artist. Defaults to a single random album, since an artist must have at least one. /// The created domain aggregate root. public Artist Create( LibraryId? libraryId = null, string? name = null, + Optional? sortName = null, + Optional? disambiguation = null, + Optional? type = null, + Optional? gender = null, + Optional? country = null, + Optional? area = null, + Optional? beginArea = null, + Optional? endArea = null, + Optional? lifeSpanBegin = null, + Optional? lifeSpanEnd = null, + bool? isEnded = null, Optional? website = null, Optional? musicBrainzArtistId = null, + List? ipis = null, + List? isnis = null, + List? aliases = null, + List? genres = null, + List? tags = null, + List? ratings = null, List? contributors = null, List? albums = null) { + int lifeSpanBeginYear = Random.Shared.Next(MINIMUM_LIFESPAN_YEAR, MAXIMUM_LIFESPAN_YEAR); + int lifeSpanEndYear = Random.Shared.Next(lifeSpanBeginYear, Math.Max(lifeSpanBeginYear + 1, MAXIMUM_LIFESPAN_YEAR)); Result artistResult = Artist.Create( libraryId ?? _libraryIdFixture.Create(), name ?? _faker.Name.FullName(), + sortName ?? Optional.Some(_faker.Name.FullName()), + disambiguation ?? Optional.Some(_faker.Lorem.Sentence()), + type ?? Optional.Some(_faker.PickRandom()), + gender ?? Optional.Some(_faker.PickRandom()), + country ?? Optional.Some(_faker.Address.CountryCode()), + area ?? Optional.Some(_musicAreaFixture.Create()), + beginArea ?? Optional.Some(_musicAreaFixture.Create()), + endArea ?? Optional.Some(_musicAreaFixture.Create()), + lifeSpanBegin ?? Optional.Some(new DateOnly(lifeSpanBeginYear, 1, 1)), + lifeSpanEnd ?? Optional.Some(new DateOnly(lifeSpanEndYear, 1, 1)), + isEnded ?? _faker.Random.Bool(), website ?? Optional.Some(_faker.Internet.Url()), musicBrainzArtistId ?? Optional.Some(_musicBrainzIdFixture.Create()), + ipis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(9))], + isnis ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.AlphaNumeric(16))], + aliases ?? _musicArtistAliasFixture.CreateMany(_faker.Random.Int(1, 2)), + genres ?? _genreFixture.CreateMany(_faker.Random.Int(1, 2)), + tags ?? _tagFixture.CreateMany(_faker.Random.Int(1, 2)), + ratings ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _audioRatingFixture.Create())], contributors ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _musicMediaContributorFixture.Create())], albums ?? [_albumFixture.Create()]); diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumFixture.cs index d161f7b0..819cde1e 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumFixture.cs @@ -32,9 +32,14 @@ public class AlbumFixture /// Creates a random valid domain entity. /// /// Optional. The album metadata of the album. + /// Optional. The disambiguation comment of the album. /// Optional. The physical or digital medium of the album. + /// Optional. The outermost physical packaging of the album. + /// Optional. The script used by the language of the release of the album. /// Optional. The barcode of the album. /// Optional. The catalog number of the album. + /// Optional. The name of the label that issued the album. + /// Optional. The ASIN of the album. /// Optional. The MusicBrainz identifier of the release. /// Optional. The MusicBrainz identifier of the release group. /// Optional. The MusicBrainz identifier of the release artist. @@ -44,9 +49,14 @@ public class AlbumFixture /// The created domain entity. public Album Create( AlbumMetadata? metadata = null, + Optional? disambiguation = null, Optional? mediaFormat = null, + Optional? packaging = null, + Optional? script = null, Optional? barcode = null, - Optional? catalogNumber = null, + List? catalogNumbers = null, + Optional? label = null, + Optional? asin = null, Optional? musicBrainzReleaseId = null, Optional? musicBrainzReleaseGroupId = null, Optional? musicBrainzReleaseArtistId = null, @@ -56,9 +66,14 @@ public class AlbumFixture { Result albumResult = Album.Create( metadata ?? _albumMetadataFixture.Create(), + disambiguation ?? Optional.Some(_faker.Lorem.Sentence()), mediaFormat ?? Optional.Some(_faker.PickRandom()), + packaging ?? Optional.Some(_faker.PickRandom()), + script ?? Optional.Some(_faker.Random.String2(4)), barcode ?? Optional.Some(_barcodeFixture.Create()), - catalogNumber ?? Optional.Some(_faker.Random.String2(_faker.Random.Int(5, 20))), + catalogNumbers ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _faker.Random.String2(_faker.Random.Int(5, 20)))], + label ?? Optional.Some(_faker.Company.CompanyName()), + asin ?? Optional.Some(_faker.Random.AlphaNumeric(10)), musicBrainzReleaseId ?? Optional.Some(_musicBrainzIdFixture.Create()), musicBrainzReleaseGroupId ?? Optional.Some(_musicBrainzIdFixture.Create()), musicBrainzReleaseArtistId ?? Optional.Some(_musicBrainzIdFixture.Create()), diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackFixture.cs index 6432d8ed..7a4920b7 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackFixture.cs @@ -29,6 +29,7 @@ public class TrackFixture private readonly IsrcFixture _isrcFixture = new(); private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly MusicWorkFixture _musicWorkFixture = new(); private readonly AudioRatingFixture _audioRatingFixture = new(); /// @@ -36,51 +37,54 @@ public class TrackFixture /// /// Optional. The file system path of the track. /// Optional. The audio metadata of the track. + /// Optional. The disambiguation comment of the track. /// Optional. The number of the track on its disc. /// Optional. The number of the disc the track belongs to. /// Optional. The moods of the track. /// Optional. The script used by the language of the track. /// Optional. The musical key of the track. /// Optional. The tempo of the track in beats per minute. + /// Optional. Whether the recording of the track is a video recording. /// Optional. The ISRCs of the track. - /// Optional. The title of the work the track is a recording of. + /// Optional. The work the track is a recording of. /// Optional. The MusicBrainz identifier of the recording. /// Optional. The MusicBrainz identifier of the track. - /// Optional. The MusicBrainz identifier of the work. /// Optional. The media contributors of the track. /// Optional. The ratings of the track. /// The created domain entity. public Track Create( string? path = null, AudioMetadata? metadata = null, + Optional? disambiguation = null, int? trackNumber = null, Optional? discNumber = null, List? moods = null, Optional? script = null, Optional? key = null, Optional? bpm = null, + bool? isVideo = null, List? isrcs = null, - Optional? work = null, + Optional? work = null, Optional? musicBrainzRecordingId = null, Optional? musicBrainzTrackId = null, - Optional? musicBrainzWorkId = null, List? contributors = null, List? ratings = null) { Result trackResult = Track.Create( path ?? _faker.System.FilePath(), metadata ?? _audioMetadataFixture.Create(), + disambiguation ?? Optional.None(), trackNumber ?? _faker.Random.Int(1, 30), discNumber ?? Optional.Some(_faker.Random.Int(1, 2)), moods ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _moodFixture.Create())], script ?? Optional.Some(_faker.Lorem.Word()), key ?? Optional.Some(_faker.PickRandom()), bpm ?? Optional.Some(_faker.Random.Int(60, 220)), + isVideo ?? _faker.Random.Bool(), isrcs ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _isrcFixture.Create())], - work ?? Optional.Some(_faker.Lorem.Sentence()), + work ?? Optional.Some(_musicWorkFixture.Create()), musicBrainzRecordingId ?? Optional.Some(_musicBrainzIdFixture.Create()), musicBrainzTrackId ?? Optional.Some(_musicBrainzIdFixture.Create()), - musicBrainzWorkId ?? Optional.Some(_musicBrainzIdFixture.Create()), contributors ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _musicMediaContributorFixture.Create())], ratings ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _audioRatingFixture.Create())]); diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataFixture.cs index b3776200..5a5d8606 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataFixture.cs @@ -30,13 +30,14 @@ public class AlbumMetadataFixture /// /// Optional. The title of the album. /// Optional. The original title of the album. + /// Optional. The title of the specific release (edition) of the album. /// Optional. The description of the album. /// Optional. The release information of the album. /// Optional. The genres of the album. /// Optional. The tags associated with the album. /// Optional. The language of the album. /// Optional. The original language of the album. - /// Optional. The type of the release. + /// Optional. The types of the release. /// Optional. The status of the release. /// Optional. The number of discs of the release. /// Optional. The number of tracks of the release. @@ -44,13 +45,14 @@ public class AlbumMetadataFixture public AlbumMetadata Create( string? title = null, Optional? originalTitle = null, + Optional? releaseTitle = null, Optional? description = null, ReleaseInfo? releaseInfo = null, List? genres = null, List? tags = null, Optional? language = null, Optional? originalLanguage = null, - Optional? releaseType = null, + List? releaseTypes = null, Optional? releaseStatus = null, Optional? totalDiscs = null, int? totalTracks = null) @@ -58,13 +60,14 @@ public class AlbumMetadataFixture Result metadataResult = AlbumMetadata.Create( title ?? _faker.Commerce.ProductName(), originalTitle ?? Optional.None(), + releaseTitle ?? Optional.Some(_faker.Commerce.ProductName()), description ?? Optional.Some(_faker.Lorem.Sentence()), releaseInfo ?? _releaseInfoFixture.Create(), genres ?? [_genreFixture.Create(), _genreFixture.Create()], tags ?? [_tagFixture.Create(), _tagFixture.Create()], language ?? Optional.Some(_languageInfoFixture.Create()), originalLanguage ?? Optional.None(), - releaseType ?? Optional.Some(_faker.PickRandom()), + releaseTypes ?? [_faker.PickRandom()], releaseStatus ?? Optional.Some(_faker.PickRandom()), totalDiscs ?? Optional.Some(_faker.Random.Int(1, 4)), totalTracks ?? _faker.Random.Int(1, 50)); diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicAreaFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicAreaFixture.cs new file mode 100644 index 00000000..94fea40f --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicAreaFixture.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MusicAreaFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The MusicBrainz identifier of the area. + /// Optional. The name of the area. + /// Optional. The sort name of the area. + /// Optional. The disambiguation comment of the area. + /// Optional. The MusicBrainz type of the area. + /// Optional. The ISO 3166 code of the area. + /// The created . + public MusicArea Create( + MusicBrainzId? musicBrainzAreaId = null, + string? name = null, + Optional? sortName = null, + Optional? disambiguation = null, + Optional? type = null, + Optional? iso3166Code = null) + { + Result areaResult = MusicArea.Create( + musicBrainzAreaId ?? _musicBrainzIdFixture.Create(), + name ?? _faker.Address.Country(), + sortName ?? Optional.Some(_faker.Address.Country()), + disambiguation ?? Optional.Some(_faker.Lorem.Sentence()), + type ?? Optional.Some(_faker.Random.ArrayElement(["Country", "City", "Area"])), + iso3166Code ?? Optional.Some(_faker.Address.CountryCode())); + + if (areaResult.IsFailure) + throw new System.InvalidOperationException("Failed to create MusicArea: " + string.Join(", ", areaResult.Errors)); + return areaResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAliasFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAliasFixture.cs new file mode 100644 index 00000000..f1a868eb --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAliasFixture.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MusicArtistAliasFixture +{ + private const int MINIMUM_ALIAS_YEAR = 1900; + private const int MAXIMUM_ALIAS_YEAR = 2026; + + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the alias. + /// Optional. The sort name of the alias. + /// Optional. The type of the alias. + /// Optional. The locale the alias is used in. + /// Optional. Whether this is the primary alias of the artist. + /// Optional. The date the alias began being used. + /// Optional. The date the alias stopped being used. + /// Optional. Whether the alias is no longer used. + /// The created . + public MusicArtistAlias Create( + string? name = null, + Optional? sortName = null, + Optional? type = null, + Optional? locale = null, + bool? isPrimary = null, + Optional? beginDate = null, + Optional? endDate = null, + bool? isEnded = null) + { + int beginYear = Random.Shared.Next(MINIMUM_ALIAS_YEAR, MAXIMUM_ALIAS_YEAR); + int endYear = Random.Shared.Next(beginYear, Math.Max(beginYear + 1, MAXIMUM_ALIAS_YEAR)); + Result aliasResult = MusicArtistAlias.Create( + name ?? _faker.Name.FullName(), + sortName ?? Optional.Some(_faker.Name.FullName()), + type ?? Optional.Some(_faker.Random.ArrayElement(["Artist name", "Search hint"])), + locale ?? Optional.Some(_faker.Random.String2(2)), + isPrimary ?? _faker.Random.Bool(), + beginDate ?? Optional.Some(new DateOnly(beginYear, 1, 1)), + endDate ?? Optional.Some(new DateOnly(endYear, 1, 1)), + isEnded ?? _faker.Random.Bool()); + + if (aliasResult.IsFailure) + throw new InvalidOperationException("Failed to create MusicArtistAlias: " + string.Join(", ", aliasResult.Errors)); + return aliasResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataFixture.cs new file mode 100644 index 00000000..4c6f06ff --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataFixture.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryPathMetadataFixture +{ + private readonly Faker _faker = new(); + private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the artist derived from the path. + /// Optional. The type of the release derived from the path. + /// Optional. The release year derived from the path. + /// Optional. The name of the release derived from the path. + /// Optional. The number of the track derived from the path. + /// Optional. The number of the disc the track belongs to, derived from the path. + /// Optional. The title of the track derived from the path. + /// Whether the artist name should be captured. When , the artist name is not captured. + /// Whether the release type should be captured. When , the release type is not captured. + /// Whether the release year should be captured. When , the release year is not captured. + /// Whether the release name should be captured. When , the release name is not captured. + /// Whether the track number should be captured. When , the track number is not captured. + /// Whether the disc number should be captured. When , the disc number is not captured. + /// Whether the track title should be captured. When , the track title is not captured. + /// The created . + public MusicLibraryPathMetadata Create( + string? artistName = null, + MusicReleaseType? releaseType = null, + int? releaseYear = null, + string? releaseName = null, + int? trackNumber = null, + int? discNumber = null, + string? trackTitle = null, + bool includeArtistName = true, + bool includeReleaseType = true, + bool includeReleaseYear = true, + bool includeReleaseName = true, + bool includeTrackNumber = true, + bool includeDiscNumber = true, + bool includeTrackTitle = true) + { + Dictionary values = []; + if (includeArtistName) + values[LibraryPathPartKind.Artist] = artistName ?? _faker.Name.FullName(); + if (includeReleaseType) + values[LibraryPathPartKind.ReleaseType] = (releaseType ?? _faker.PickRandom()).ToString(); + if (includeReleaseYear) + values[LibraryPathPartKind.ReleaseYear] = (releaseYear ?? _faker.Random.Int(1900, 2025)).ToString(); + if (includeReleaseName) + values[LibraryPathPartKind.ReleaseName] = releaseName ?? _faker.Commerce.ProductName(); + if (includeTrackNumber) + values[LibraryPathPartKind.TrackNumber] = (trackNumber ?? _faker.Random.Int(1, 30)).ToString(); + if (includeDiscNumber) + values[LibraryPathPartKind.DiscNumber] = (discNumber ?? _faker.Random.Int(1, 4)).ToString(); + if (includeTrackTitle) + values[LibraryPathPartKind.TrackName] = trackTitle ?? _faker.Commerce.ProductName(); + return MusicLibraryPathMetadata.FromParsedLibraryPath(_parsedLibraryPathFixture.Create(values)); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWorkFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWorkFixture.cs new file mode 100644 index 00000000..d41ed5d7 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWorkFixture.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MusicWorkFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The MusicBrainz identifier of the work. + /// Optional. The title of the work. + /// Optional. The MusicBrainz type of the work. + /// Optional. The languages of the work. + /// Optional. The ISWC codes of the work. + /// The created . + public MusicWork Create( + MusicBrainzId? musicBrainzWorkId = null, + string? title = null, + Optional? type = null, + List? languages = null, + List? iswcs = null) + { + Result workResult = MusicWork.Create( + musicBrainzWorkId ?? _musicBrainzIdFixture.Create(), + title ?? _faker.Music.Genre(), + type ?? Optional.Some(_faker.Random.ArrayElement(["Song", "Instrumental"])), + languages ?? _languageInfoFixture.CreateMany(_faker.Random.Int(1, 2)), + iswcs ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => $"T{_faker.Random.AlphaNumeric(10)}")]); + + if (workResult.IsFailure) + throw new System.InvalidOperationException("Failed to create MusicWork: " + string.Join(", ", workResult.Errors)); + return workResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs index 9dfa2bee..a4a80153 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; @@ -42,6 +43,7 @@ public class LibraryFixture /// Whether metadata should be saved in the media directories. /// Whether unchanged directories should be skipped during scan. /// Optional. The scan Ids associated with the library. + /// Optional. The path template of the library. /// Whether the cover image should be included, or left unset, meaning the library has no cover. /// The created . public Library Create( @@ -57,6 +59,7 @@ public class LibraryFixture bool shouldSaveMetadataInMediaDirectories = false, bool shouldSkipUnchangedDirectoriesDuringScan = false, IEnumerable? scanIds = null, + LibraryPathTemplate? pathTemplate = null, bool includeCoverImage = true) { List validPaths = @@ -83,6 +86,7 @@ public class LibraryFixture canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, + pathTemplate ?? LibraryPathTemplate.Empty(), resolvedScanIds ) : Library.Create( @@ -97,6 +101,7 @@ public class LibraryFixture canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, + pathTemplate ?? LibraryPathTemplate.Empty(), resolvedScanIds ); diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartFixture.cs new file mode 100644 index 00000000..51b3fed1 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartFixture.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. When omitted, a representation valid for the resolved kind is generated. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathPart Create( + LibraryPathPartKind? kind = null, + string? representation = null, + bool isOptional = false) + { + LibraryPathPartKind resolvedKind = kind ?? _faker.PickRandom(); + string resolvedRepresentation = representation ?? CreateValidRepresentation(resolvedKind); + Result partResult = LibraryPathPart.Create(resolvedKind, resolvedRepresentation, isOptional); + if (partResult.IsFailure) + throw new InvalidOperationException("Failed to create LibraryPathPart: " + string.Join(", ", partResult.Errors)); + return partResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates a representation that is valid for the provided . + /// + /// The kind of the path part a representation is created for. + /// The created representation. + private string CreateValidRepresentation(LibraryPathPartKind kind) + { + // A separator renders the platform path separator, so it never carries a representation. + if (kind == LibraryPathPartKind.Separator) + return string.Empty; + // A literal is arbitrary on-disk text between value parts, so it carries no value placeholder. + if (kind == LibraryPathPartKind.Literal) + return _faker.Lorem.Word(); + // A typed part must carry exactly one value placeholder, so that the position of the captured value is unambiguous. + return "{0}"; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateFixture.cs new file mode 100644 index 00000000..a6bbf490 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateFixture +{ + private readonly Faker _faker = new(); + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The ordered parts that make up the path template. + /// Whether the template should carry parts. When , an empty template is created. + /// The created . + public LibraryPathTemplate Create( + IEnumerable? parts = null, + bool includeParts = true) + { + if (!includeParts) + return LibraryPathTemplate.Empty(); + return LibraryPathTemplate.Create(parts ?? _libraryPathPartFixture.CreateMany(_faker.Random.Int(1, 4))); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionFixture.cs new file mode 100644 index 00000000..9b2b6ba0 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartDefinitionFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The kind of the described part. + /// Optional. The value type captured by the described part. + /// Optional. The default representation of the described part. + /// Whether the described part is optional by default. + /// The created . + public LibraryPathPartDefinition Create( + LibraryPathPartKind? kind = null, + LibraryPathValueType? valueType = null, + string? defaultRepresentation = null, + bool isOptionalByDefault = false) + { + return new LibraryPathPartDefinition( + kind ?? _faker.PickRandom(), + valueType ?? _faker.PickRandom(), + defaultRepresentation ?? "{0}", + isOptionalByDefault); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathFixture.cs new file mode 100644 index 00000000..fe6f1ee8 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathFixture.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class ParsedLibraryPathFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The captured values, keyed by their part kind. + /// Whether the parsed path should carry captured values. When , an empty set of values is created. + /// The created . + public ParsedLibraryPath Create( + IReadOnlyDictionary? values = null, + bool includeValues = true) + { + if (!includeValues) + return ParsedLibraryPath.Create(new Dictionary()); + return ParsedLibraryPath.Create(values ?? CreateRandomValues()); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates a bounded set of random captured values. + /// + /// The captured values, keyed by their part kind. + private Dictionary CreateRandomValues() + { + LibraryPathPartKind[] candidateKinds = + [ + LibraryPathPartKind.Artist, + LibraryPathPartKind.ReleaseName, + LibraryPathPartKind.TrackName, + LibraryPathPartKind.Title, + LibraryPathPartKind.Author + ]; + + Dictionary values = []; + foreach (LibraryPathPartKind kind in candidateKinds.Take(_faker.Random.Int(1, candidateKinds.Length))) + values[kind] = _faker.Lorem.Word(); + return values; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs index f41719d0..066592cc 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs @@ -25,6 +25,7 @@ public class UserSettingsFixture /// Whether the "The" prefix of library item titles is ignored by the alpha picker. /// Whether the theme data served to this user is cached. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. + /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Whether PDF books are rendered as page images for the user. /// Whether the styles of the book content are preserved when it is rendered for the user. /// The created . @@ -35,6 +36,7 @@ public class UserSettingsFixture bool shouldIgnoreThePrefixForAlphaPicker = false, bool isThemeCachingEnabled = true, bool shouldAggregateMetadataWhenMissing = false, + bool shouldAggregateArtworkWhenMissing = false, bool shouldRenderPdfAsImages = false, bool shouldPreserveBookStyles = true) { @@ -45,6 +47,7 @@ public class UserSettingsFixture shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing, + shouldAggregateArtworkWhenMissing, shouldRenderPdfAsImages, shouldPreserveBookStyles); return settings.Value; diff --git a/tests/Common/Lumina.Domain.Fixtures/Lumina.Domain.Fixtures.csproj b/tests/Common/Lumina.Domain.Fixtures/Lumina.Domain.Fixtures.csproj index 7450b785..f46cfe4b 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Lumina.Domain.Fixtures.csproj +++ b/tests/Common/Lumina.Domain.Fixtures/Lumina.Domain.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Lumina.Domain.SharedKernel.Fixtures.csproj b/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Lumina.Domain.SharedKernel.Fixtures.csproj index aa694200..e0f3bddb 100644 --- a/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Lumina.Domain.SharedKernel.Fixtures.csproj +++ b/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Lumina.Domain.SharedKernel.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Validation/ValidationOptionsFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Validation/ValidationOptionsFixture.cs index 32da0140..77db29b5 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Validation/ValidationOptionsFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Validation/ValidationOptionsFixture.cs @@ -5,10 +5,17 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Infrastructure.Fixtures.Common.Validation; /// -/// Test-support placeholder class for validation options tests. +/// Test-support placeholder options type used as the validated options in validation options tests. /// [ExcludeFromCodeCoverage] public class ValidationOptionsFixture { - + /// + /// Creates a new instance. + /// + /// A configured instance. + public ValidationOptionsFixture Create() + { + return new ValidationOptionsFixture(); + } } diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs index af851c44..552cee68 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Infrastructure.Core.Authorization; using System; @@ -16,6 +18,13 @@ namespace Lumina.Infrastructure.Fixtures.Core.Authorization; [ExcludeFromCodeCoverage] public class AuthorizationServiceFixture { + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); + private readonly UserRoleEntityFixture _userRoleEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); + /// /// Creates a user entity with specified permissions and roles. /// @@ -28,7 +37,6 @@ public class AuthorizationServiceFixture { Guid userId = Guid.NewGuid(); DateTime utcNow = DateTime.UtcNow; - List userPermissions = []; UserRoleEntity? userRole = null; if (rolePermissions is not null) @@ -36,86 +44,63 @@ public class AuthorizationServiceFixture foreach (KeyValuePair> rolePerm in rolePermissions) { Guid roleId = Guid.NewGuid(); - RoleEntity role = new() - { - Id = roleId, - RoleName = rolePerm.Key, - CreatedOnUtc = utcNow, - CreatedBy = userId, - RolePermissions = [] - }; + RoleEntity role = _roleEntityFixture.Create( + id: roleId, + roleName: rolePerm.Key, + createdBy: userId, + createdOnUtc: utcNow); foreach (AuthorizationPermission permission in rolePerm.Value) { Guid permissionId = Guid.NewGuid(); - PermissionEntity permissionEntity = new() - { - Id = permissionId, - PermissionName = permission, - CreatedOnUtc = utcNow, - CreatedBy = userId - }; + PermissionEntity permissionEntity = _permissionEntityFixture.Create( + id: permissionId, + permissionName: permission, + createdBy: userId, + createdOnUtc: utcNow); - role.RolePermissions.Add(new RolePermissionEntity - { - Id = Guid.NewGuid(), - RoleId = roleId, - Role = role, - PermissionId = permissionId, - Permission = permissionEntity, - CreatedOnUtc = utcNow, - CreatedBy = userId - }); + role.RolePermissions.Add(_rolePermissionEntityFixture.Create( + role: role, + permission: permissionEntity, + createdBy: userId, + createdOnUtc: utcNow)); } - userRole = new UserRoleEntity - { - Id = Guid.NewGuid(), - UserId = userId, - User = null!, - RoleId = roleId, - Role = role, - CreatedOnUtc = utcNow, - CreatedBy = userId - }; + userRole = _userRoleEntityFixture.Create( + userId: userId, + roleId: roleId, + role: role, + includeUser: false, + createdBy: userId, + createdOnUtc: utcNow); } } - UserEntity user = new() - { - Id = userId, - Username = "test-user", - Password = "hashed-password", - CreatedOnUtc = utcNow, - CreatedBy = userId, - Libraries = [], - UserPermissions = userPermissions, - UserRole = userRole - }; + UserEntity user = _userEntityFixture.Create( + username: "test-user", + password: "hashed-password", + id: userId, + userRole: userRole, + includeUserRole: true, + createdBy: userId, + createdOnUtc: utcNow); if (directPermissions is not null) { foreach (AuthorizationPermission permission in directPermissions) { Guid permissionId = Guid.NewGuid(); - PermissionEntity permissionEntity = new() - { - Id = permissionId, - PermissionName = permission, - CreatedOnUtc = utcNow, - CreatedBy = userId - }; + PermissionEntity permissionEntity = _permissionEntityFixture.Create( + id: permissionId, + permissionName: permission, + createdBy: userId, + createdOnUtc: utcNow); - userPermissions.Add(new UserPermissionEntity - { - Id = Guid.NewGuid(), - UserId = userId, - User = user, - PermissionId = permissionId, - Permission = permissionEntity, - CreatedOnUtc = utcNow, - CreatedBy = userId - }); + user.UserPermissions.Add(_userPermissionEntityFixture.Create( + user, + permissionEntity, + createdOnUtc: utcNow, + createdBy: userId)); } } diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Security/CryptographyServiceFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Security/CryptographyServiceFixture.cs index e00e0e2a..0e3a4783 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Security/CryptographyServiceFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Security/CryptographyServiceFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; using Microsoft.Extensions.Options; using NSubstitute; using System; @@ -16,21 +17,20 @@ namespace Lumina.Infrastructure.Fixtures.Core.Security; [ExcludeFromCodeCoverage] public class CryptographyServiceFixture { + private readonly EncryptionSettingsDtoFixture _encryptionSettingsDtoFixture = new(); + /// /// Creates a valid encryption settings model for testing. /// /// The configured options. - public static IOptions CreateEncryptionSettings() + public IOptions CreateEncryptionSettings() { // Generate a valid 256-bit (32 byte) key for AES-256 byte[] key = new byte[32]; RandomNumberGenerator.Fill(key); string base64Key = Convert.ToBase64String(key); - EncryptionSettingsDto settings = new() - { - SecretKey = base64Key - }; + EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: base64Key); IOptions options = Substitute.For>(); options.Value.Returns(settings); @@ -42,7 +42,7 @@ public class CryptographyServiceFixture /// Creates test data for encryption/decryption. /// /// A string to be encrypted/decrypted. - public static string CreateTestData() + public string CreateTestData() { return new Faker().Lorem.Sentence(); } diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Lumina.Infrastructure.Fixtures.csproj b/tests/Common/Lumina.Infrastructure.Fixtures/Lumina.Infrastructure.Fixtures.csproj index 79ec9e66..76f36e26 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Lumina.Infrastructure.Fixtures.csproj +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Lumina.Infrastructure.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false @@ -20,5 +19,6 @@ + diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj index bacaf455..b32a8658 100644 --- a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs index 98b6ab94..7720d67d 100644 --- a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs @@ -13,9 +13,10 @@ using System.Runtime.InteropServices; // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] -// The following GUID is for the ID of the typelib if this project is exposed to COM +// The following GUID is for the ID of the typelib if this project is exposed to COM. [assembly: Guid("B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.SecurityTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.Contracts.Fixtures/Lumina.Plugins.Contracts.Fixtures.csproj b/tests/Common/Lumina.Plugins.Contracts.Fixtures/Lumina.Plugins.Contracts.Fixtures.csproj index 6509accf..6ee15563 100644 --- a/tests/Common/Lumina.Plugins.Contracts.Fixtures/Lumina.Plugins.Contracts.Fixtures.csproj +++ b/tests/Common/Lumina.Plugins.Contracts.Fixtures/Lumina.Plugins.Contracts.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseFixture.cs b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseFixture.cs new file mode 100644 index 00000000..028fcb86 --- /dev/null +++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class CoverArtArchiveArtworkResponseFixture +{ + private readonly CoverArtArchiveImageResponseFixture _coverArtArchiveImageResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The images of the artwork. + /// Whether the images should be included, or forced to . + /// A configured instance. + public CoverArtArchiveArtworkResponse Create( + List? images = null, + bool includeImages = true) + { + return new CoverArtArchiveArtworkResponse + { + Images = includeImages ? images ?? [.. _coverArtArchiveImageResponseFixture.CreateMany()] : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseFixture.cs b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseFixture.cs new file mode 100644 index 00000000..72d9f7c1 --- /dev/null +++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseFixture.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class CoverArtArchiveImageResponseFixture +{ + private static readonly string[] s_knownTypes = + [ + "Front", "Back", "Booklet", "Medium", "Tray", "Spine", "Obi", "Sticker", "Poster", "Liner", "Watermark", "Other" + ]; + + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The URL of the full size image. + /// Whether the image URL should be included, or forced to . + /// Optional. The URL of the thumbnail of the image. + /// Optional. The types of the image. + /// Whether the types should be included, or forced to . + /// Optional. Whether the image is the front cover. + /// Optional. Whether the image is the back cover. + /// Optional. The comment describing the image. + /// A configured instance. + public CoverArtArchiveImageResponse Create( + string? image = null, + bool includeImage = true, + string? thumbnail = null, + List? types = null, + bool includeTypes = true, + bool? isFront = null, + bool? isBack = null, + string? comment = null) + { + return new CoverArtArchiveImageResponse + { + Image = includeImage ? image ?? $"https://coverartarchive.org/release/{Guid.NewGuid():D}/{_faker.Random.Long(1, 999_999_999)}.jpg" : null, + Thumbnail = thumbnail ?? $"https://coverartarchive.org/release/{Guid.NewGuid():D}/thumb.jpg", + Types = includeTypes ? types ?? [_faker.PickRandom(s_knownTypes)] : null, + IsFront = isFront ?? _faker.Random.Bool(), + IsBack = isBack ?? _faker.Random.Bool(), + Comment = comment ?? _faker.Lorem.Sentence() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/DTO/Settings/CoverArtArchiveSettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/DTO/Settings/CoverArtArchiveSettingsDtoFixture.cs new file mode 100644 index 00000000..43b7818b --- /dev/null +++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Common/Models/DTO/Settings/CoverArtArchiveSettingsDtoFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class CoverArtArchiveSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The user agent sent with every request. + /// Optional. The contact email sent to the Cover Art Archive API. + /// Whether the contact email should be included, or forced to . + /// Optional. The minimum interval between consecutive requests. + /// A configured instance. + public CoverArtArchiveSettingsDto Create( + string? userAgent = null, + string? contactEmail = null, + bool includeContactEmail = true, + TimeSpan? minimumRequestInterval = null) + { + return new CoverArtArchiveSettingsDto + { + UserAgent = userAgent ?? $"Lumina-CoverArtArchive/{_faker.Random.Int(1, 9)}.{_faker.Random.Int(0, 9)}", + ContactEmail = includeContactEmail ? contactEmail ?? _faker.Internet.Email() : null, + MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromSeconds(_faker.Random.Double(0, 5)) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Lumina.Plugins.CoverArtArchive.Fixtures.csproj b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Lumina.Plugins.CoverArtArchive.Fixtures.csproj new file mode 100644 index 00000000..0daa7443 --- /dev/null +++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Lumina.Plugins.CoverArtArchive.Fixtures.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + false + false + false + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..30f3a862 --- /dev/null +++ b/tests/Common/Lumina.Plugins.CoverArtArchive.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.CoverArtArchive.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.CoverArtArchive.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("D4E2F7A1-8B3C-4D5E-A6F1-2B3C4D5E6F70")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.SecurityTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.Epub.Fixtures/Lumina.Plugins.Epub.Fixtures.csproj b/tests/Common/Lumina.Plugins.Epub.Fixtures/Lumina.Plugins.Epub.Fixtures.csproj index 4c13ed39..c921a494 100644 --- a/tests/Common/Lumina.Plugins.Epub.Fixtures/Lumina.Plugins.Epub.Fixtures.csproj +++ b/tests/Common/Lumina.Plugins.Epub.Fixtures/Lumina.Plugins.Epub.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Plugins.ID3.Fixtures/Common/Models/DTO/Tags/Id3TagDtoFixture.cs b/tests/Common/Lumina.Plugins.ID3.Fixtures/Common/Models/DTO/Tags/Id3TagDtoFixture.cs new file mode 100644 index 00000000..a79ce840 --- /dev/null +++ b/tests/Common/Lumina.Plugins.ID3.Fixtures/Common/Models/DTO/Tags/Id3TagDtoFixture.cs @@ -0,0 +1,253 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.Fixtures.Common.Models.DTO.Tags; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class Id3TagDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The title of the track. + /// Whether the title should be included, or forced to . + /// Optional. The title of the album the track belongs to. + /// Whether the album should be included, or forced to . + /// Optional. The artists credited on the track. + /// Optional. The artists credited on the album. + /// Optional. The sort name of the album artist. + /// Whether the album artist sort name should be included, or forced to . + /// Optional. The sort name of the track artist. + /// Whether the track artist sort name should be included, or forced to . + /// Optional. The number of the track on its disc, or a random one when not supplied. + /// Optional. The number of tracks on the disc, or a random one when not supplied. + /// Optional. The number of the disc the track belongs to, or a random one when not supplied. + /// Optional. The number of discs of the release, or a random one when not supplied. + /// Optional. The year the track was released. + /// Whether the year should be included, or forced to . + /// Optional. The original release date of the track. + /// Whether the original release date should be included, or forced to . + /// Optional. The original release year of the track. + /// Whether the original release year should be included, or forced to . + /// Optional. The genres the tags associate with the track. + /// Optional. The composers credited on the track. + /// Optional. The lyricists credited on the track. + /// Optional. The conductors credited on the track. + /// Optional. The remixers credited on the track. + /// Optional. The people credited on the track, each with their role. + /// Optional. The language of the track. + /// Whether the language should be included, or forced to . + /// Optional. The script used by the language of the track. + /// Whether the script should be included, or forced to . + /// Optional. The label that issued the album. + /// Whether the label should be included, or forced to . + /// Optional. The catalog numbers of the album. + /// Optional. The barcode of the album. + /// Whether the barcode should be included, or forced to . + /// Optional. The types of the release. + /// Optional. The status of the release. + /// Whether the release status should be included, or forced to . + /// Optional. The country the release was issued in. + /// Whether the release country should be included, or forced to . + /// Optional. The medium of the release. + /// Whether the media format should be included, or forced to . + /// Optional. The packaging of the release. + /// Whether the packaging should be included, or forced to . + /// Optional. The ASIN of the album. + /// Whether the ASIN should be included, or forced to . + /// Optional. The ISRCs of the track. + /// Optional. The moods of the track. + /// Optional. The title of the work the track is a recording of. + /// Whether the work title should be included, or forced to . + /// Optional. The musical key of the track. + /// Whether the musical key should be included, or forced to . + /// Optional. The tempo of the track in beats per minute. + /// Whether the tempo should be included, or forced to . + /// Optional. The duration of the audio of the track in seconds. + /// Whether the duration should be included, or forced to . + /// Optional. The sample rate of the audio of the track in Hz. + /// Whether the sample rate should be included, or forced to . + /// Optional. The number of audio channels of the track. + /// Whether the channel count should be included, or forced to . + /// Optional. The bit depth of the audio of the track. + /// Whether the bit depth should be included, or forced to . + /// Optional. The bitrate of the audio of the track in kbps. + /// Whether the bitrate should be included, or forced to . + /// Optional. The description of the audio codec of the track. + /// Whether the audio codec should be included, or forced to . + /// Optional. The official website associated with the artist. + /// Whether the website should be included, or forced to . + /// Optional. The MusicBrainz identifier of the artist. + /// Whether the MusicBrainz artist identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the release artist. + /// Whether the MusicBrainz release artist identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the release group. + /// Whether the MusicBrainz release group identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the release. + /// Whether the MusicBrainz release identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the recording of the track. + /// Whether the MusicBrainz recording identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the track on its release. + /// Whether the MusicBrainz release track identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the work the track is a recording of. + /// Whether the MusicBrainz work identifier should be included, or forced to . + /// A configured instance. + public Id3TagDto Create( + string? title = null, + bool includeTitle = true, + string? album = null, + bool includeAlbum = true, + List? trackArtists = null, + List? albumArtists = null, + string? albumArtistSortName = null, + bool includeAlbumArtistSortName = true, + string? trackArtistSortName = null, + bool includeTrackArtistSortName = true, + uint? trackNumber = null, + uint? trackCount = null, + uint? discNumber = null, + uint? discCount = null, + int? year = null, + bool includeYear = true, + DateOnly? originalReleaseDate = null, + bool includeOriginalReleaseDate = true, + int? originalReleaseYear = null, + bool includeOriginalReleaseYear = true, + List? genres = null, + List? composers = null, + List? lyricists = null, + List? conductors = null, + List? remixers = null, + List<(string Role, string Name)>? involvedPeople = null, + string? language = null, + bool includeLanguage = true, + string? script = null, + bool includeScript = true, + string? label = null, + bool includeLabel = true, + List? catalogNumbers = null, + string? barcode = null, + bool includeBarcode = true, + List? releaseTypes = null, + string? releaseStatus = null, + bool includeReleaseStatus = true, + string? releaseCountry = null, + bool includeReleaseCountry = true, + string? mediaFormat = null, + bool includeMediaFormat = true, + string? packaging = null, + bool includePackaging = true, + string? asin = null, + bool includeAsin = true, + List? isrcs = null, + List? moods = null, + string? workTitle = null, + bool includeWorkTitle = true, + string? musicKey = null, + bool includeMusicKey = true, + int? bpm = null, + bool includeBpm = true, + int? durationInSeconds = null, + bool includeDurationInSeconds = true, + int? sampleRate = null, + bool includeSampleRate = true, + int? channels = null, + bool includeChannels = true, + int? bitDepth = null, + bool includeBitDepth = true, + int? bitrate = null, + bool includeBitrate = true, + string? audioCodec = null, + bool includeAudioCodec = true, + string? website = null, + bool includeWebsite = true, + string? musicBrainzArtistId = null, + bool includeMusicBrainzArtistId = true, + string? musicBrainzReleaseArtistId = null, + bool includeMusicBrainzReleaseArtistId = true, + string? musicBrainzReleaseGroupId = null, + bool includeMusicBrainzReleaseGroupId = true, + string? musicBrainzReleaseId = null, + bool includeMusicBrainzReleaseId = true, + string? musicBrainzRecordingId = null, + bool includeMusicBrainzRecordingId = true, + string? musicBrainzReleaseTrackId = null, + bool includeMusicBrainzReleaseTrackId = true, + string? musicBrainzWorkId = null, + bool includeMusicBrainzWorkId = true) + { + return new Id3TagDto + { + Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null, + Album = includeAlbum ? album ?? _faker.Lorem.Sentence(2) : null, + TrackArtists = trackArtists ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + AlbumArtists = albumArtists ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + AlbumArtistSortName = includeAlbumArtistSortName ? albumArtistSortName ?? _faker.Name.LastName() : null, + TrackArtistSortName = includeTrackArtistSortName ? trackArtistSortName ?? _faker.Name.LastName() : null, + TrackNumber = trackNumber ?? (uint)_faker.Random.Int(1, 30), + TrackCount = trackCount ?? (uint)_faker.Random.Int(1, 30), + DiscNumber = discNumber ?? (uint)_faker.Random.Int(1, 4), + DiscCount = discCount ?? (uint)_faker.Random.Int(1, 4), + Year = includeYear ? year ?? _faker.Random.Int(1950, 2024) : null, + OriginalReleaseDate = includeOriginalReleaseDate ? originalReleaseDate ?? DateOnly.FromDateTime(_faker.Date.Past()) : null, + OriginalReleaseYear = includeOriginalReleaseYear ? originalReleaseYear ?? _faker.Random.Int(1950, 2024) : null, + Genres = genres ?? [.. _faker.Make(2, () => _faker.Lorem.Word())], + Composers = composers ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + Lyricists = lyricists ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + Conductors = conductors ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + Remixers = remixers ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + InvolvedPeople = involvedPeople ?? [(_faker.PickRandom("producer", "engineer", "mixer"), _faker.Name.FullName())], + Language = includeLanguage ? language ?? _faker.Random.String2(3, "abcdefghijklmnopqrstuvwxyz") : null, + Script = includeScript ? script ?? _faker.Random.String2(4, "abcdefghijklmnopqrstuvwxyz") : null, + Label = includeLabel ? label ?? _faker.Company.CompanyName() : null, + CatalogNumbers = catalogNumbers ?? [.. _faker.Make(2, () => _faker.Random.AlphaNumeric(8))], + Barcode = includeBarcode ? barcode ?? _faker.Random.AlphaNumeric(12) : null, + ReleaseTypes = releaseTypes ?? [_faker.PickRandom("album", "single", "ep")], + ReleaseStatus = includeReleaseStatus ? releaseStatus ?? _faker.PickRandom("official", "promotion") : null, + ReleaseCountry = includeReleaseCountry ? releaseCountry ?? _faker.PickRandom("US", "GB", "DE") : null, + MediaFormat = includeMediaFormat ? mediaFormat ?? _faker.PickRandom("CD", "Vinyl") : null, + Packaging = includePackaging ? packaging ?? _faker.PickRandom("Jewel Case", "Digipak") : null, + Asin = includeAsin ? asin ?? _faker.Random.AlphaNumeric(10) : null, + Isrcs = isrcs ?? [.. _faker.Make(2, () => $"US{_faker.Random.AlphaNumeric(10).ToUpperInvariant()}")], + Moods = moods ?? [.. _faker.Make(2, () => _faker.Lorem.Word())], + WorkTitle = includeWorkTitle ? workTitle ?? _faker.Lorem.Sentence(3) : null, + MusicKey = includeMusicKey ? musicKey ?? _faker.PickRandom("C major", "A minor") : null, + Bpm = includeBpm ? bpm ?? _faker.Random.Int(60, 200) : null, + DurationInSeconds = includeDurationInSeconds ? durationInSeconds ?? _faker.Random.Int(30, 600) : null, + SampleRate = includeSampleRate ? sampleRate ?? _faker.PickRandom(44100, 48000, 96000) : null, + Channels = includeChannels ? channels ?? _faker.Random.Int(1, 2) : null, + BitDepth = includeBitDepth ? bitDepth ?? _faker.PickRandom(16, 24, 32) : null, + Bitrate = includeBitrate ? bitrate ?? _faker.Random.Int(128, 320) : null, + AudioCodec = includeAudioCodec ? audioCodec ?? _faker.PickRandom("PCM Audio", "MPEG Audio") : null, + Website = includeWebsite ? website ?? _faker.Internet.Url() : null, + MusicBrainzArtistId = includeMusicBrainzArtistId ? musicBrainzArtistId ?? Guid.NewGuid().ToString() : null, + MusicBrainzReleaseArtistId = includeMusicBrainzReleaseArtistId ? musicBrainzReleaseArtistId ?? Guid.NewGuid().ToString() : null, + MusicBrainzReleaseGroupId = includeMusicBrainzReleaseGroupId ? musicBrainzReleaseGroupId ?? Guid.NewGuid().ToString() : null, + MusicBrainzReleaseId = includeMusicBrainzReleaseId ? musicBrainzReleaseId ?? Guid.NewGuid().ToString() : null, + MusicBrainzRecordingId = includeMusicBrainzRecordingId ? musicBrainzRecordingId ?? Guid.NewGuid().ToString() : null, + MusicBrainzReleaseTrackId = includeMusicBrainzReleaseTrackId ? musicBrainzReleaseTrackId ?? Guid.NewGuid().ToString() : null, + MusicBrainzWorkId = includeMusicBrainzWorkId ? musicBrainzWorkId ?? Guid.NewGuid().ToString() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.ID3.Fixtures/Core/Tags/TestAudioFileFactory.cs b/tests/Common/Lumina.Plugins.ID3.Fixtures/Core/Tags/TestAudioFileFactory.cs new file mode 100644 index 00000000..36ec5a00 --- /dev/null +++ b/tests/Common/Lumina.Plugins.ID3.Fixtures/Core/Tags/TestAudioFileFactory.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; +#endregion + +namespace Lumina.Plugins.ID3.Fixtures.Core.Tags; + +/// +/// Builds minimal, structurally valid WAV files used as test input for the ID3 tag reading tests. +/// The files are produced into a temporary directory at test runtime, because a WAV is a binary container whose +/// embedded tags can only be written by the tagging library itself. +/// +[ExcludeFromCodeCoverage] +public static class TestAudioFileFactory +{ + /// + /// Creates a minimal, untagged PCM WAV file. + /// + /// The path where the WAV is written. + /// The duration of the audio of the file, in milliseconds. + public static void CreateWav(string path, int durationMs = 200) + { + File.WriteAllBytes(path, BuildWav(durationMs)); + } + + /// + /// Creates a PCM WAV file whose embedded tags are configured by the provided callback. + /// + /// The path where the WAV is written. + /// The callback that configures the tags of the file. + /// The duration of the audio of the file, in milliseconds. + public static void CreateTaggedWav(string path, Action configureTags, int durationMs = 200) + { + File.WriteAllBytes(path, BuildWav(durationMs)); + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + configureTags(tagFile); + tagFile.Save(); + } + } + + /// + /// Adds a user defined text information frame (TXXX) to the ID3v2 tag of the file. + /// + /// The file whose ID3v2 tag is extended. + /// The description that identifies the frame. + /// The values of the frame. + public static void AddUserTextFrame(TagLib.File tagFile, string description, params string[] values) + { + GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.UserTextInformationFrame(description) { Text = values }); + } + + /// + /// Adds a text information frame to the ID3v2 tag of the file. + /// + /// The file whose ID3v2 tag is extended. + /// The four character identifier of the frame. + /// The values of the frame. + public static void AddTextFrame(TagLib.File tagFile, string frameId, params string[] values) + { + GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.TextInformationFrame(frameId) { Text = values }); + } + + /// + /// Adds a URL link frame (WXXX/WOAR) to the ID3v2 tag of the file. + /// + /// The file whose ID3v2 tag is extended. + /// The four character identifier of the frame. + /// The URL values of the frame. + public static void AddUrlFrame(TagLib.File tagFile, string frameId, params string[] values) + { + GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.UrlLinkFrame(frameId) { Text = values }); + } + + /// + /// Gets the ID3v2 tag of the file, creating it when the file does not carry one yet. + /// + /// The file whose ID3v2 tag is read. + /// The ID3v2 tag of the file. + private static TagLib.Id3v2.Tag GetId3v2Tag(TagLib.File tagFile) + { + return tagFile.GetTag(TagLib.TagTypes.Id3v2, true) as TagLib.Id3v2.Tag + ?? throw new InvalidOperationException("The test audio file does not expose an ID3v2 tag."); + } + + /// + /// Builds the bytes of a minimal, valid PCM WAV file with a single silent audio channel. + /// + /// The duration of the audio of the file, in milliseconds. + /// The bytes of the WAV file. + private static byte[] BuildWav(int durationMs) + { + const int SAMPLE_RATE = 44100; + const short CHANNELS = 1; + const short BITS_PER_SAMPLE = 16; + + int bytesPerSample = BITS_PER_SAMPLE / 8; + int dataSize = SAMPLE_RATE * CHANNELS * bytesPerSample * durationMs / 1000; + + using (MemoryStream memoryStream = new()) + { + using (BinaryWriter writer = new(memoryStream)) + { + writer.Write(Encoding.ASCII.GetBytes("RIFF")); + writer.Write(36 + dataSize); + writer.Write(Encoding.ASCII.GetBytes("WAVE")); + writer.Write(Encoding.ASCII.GetBytes("fmt ")); + writer.Write(16); + writer.Write((short)1); + writer.Write(CHANNELS); + writer.Write(SAMPLE_RATE); + writer.Write(SAMPLE_RATE * CHANNELS * bytesPerSample); + writer.Write((short)(CHANNELS * bytesPerSample)); + writer.Write(BITS_PER_SAMPLE); + writer.Write(Encoding.ASCII.GetBytes("data")); + writer.Write(dataSize); + writer.Write(new byte[dataSize]); + } + return memoryStream.ToArray(); + } + } +} diff --git a/tests/Common/Lumina.Plugins.ID3.Fixtures/Lumina.Plugins.ID3.Fixtures.csproj b/tests/Common/Lumina.Plugins.ID3.Fixtures/Lumina.Plugins.ID3.Fixtures.csproj new file mode 100644 index 00000000..afc4f05b --- /dev/null +++ b/tests/Common/Lumina.Plugins.ID3.Fixtures/Lumina.Plugins.ID3.Fixtures.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + false + false + false + + + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.ID3.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.ID3.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..38b23d1d --- /dev/null +++ b/tests/Common/Lumina.Plugins.ID3.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.ID3.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.ID3.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.IntegrationTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDtoFixture.cs new file mode 100644 index 00000000..0ad5598d --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class LocalMusicArtworkSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. Whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// A configured instance. + public LocalMusicArtworkSettingsDto Create( + bool? shouldExtractEmbeddedCover = null) + { + return new LocalMusicArtworkSettingsDto + { + ShouldExtractEmbeddedCover = shouldExtractEmbeddedCover ?? _faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestAudioFileFactory.cs b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestAudioFileFactory.cs new file mode 100644 index 00000000..a48164ed --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestAudioFileFactory.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; + +/// +/// Builds minimal, structurally valid WAV files used as test input for the artwork scanning and embedded cover extraction tests. +/// The files are produced into a temporary directory at test runtime, because a WAV is a binary container whose embedded pictures can only be written by the tagging library itself. +/// +[ExcludeFromCodeCoverage] +public static class TestAudioFileFactory +{ + /// + /// Creates a minimal, untagged PCM WAV file. + /// + /// The path where the WAV is written. + /// The duration of the audio of the file, in milliseconds. + public static void CreateWav(string path, int durationMs = 200) + { + WriteFile(path, BuildWav(durationMs)); + } + + /// + /// Creates a PCM WAV file that carries the provided image as its embedded front cover. + /// + /// The path where the WAV is written. + /// The bytes of the embedded cover image. + /// The MIME type of the embedded cover image, defaulting to JPEG. + /// The duration of the audio of the file, in milliseconds. + public static void CreateWavWithEmbeddedCover(string path, byte[] imageBytes, string? mimeType = "image/jpeg", int durationMs = 200) + { + CreateTaggedWav(path, tagFile => + { + tagFile.Tag.Pictures = + [ + new TagLib.Picture + { + MimeType = mimeType!, + Type = TagLib.PictureType.FrontCover, + Data = [.. imageBytes] + } + ]; + }, durationMs); + } + + /// + /// Creates a PCM WAV file whose embedded tags are configured by the provided callback. + /// + /// The path where the WAV is written. + /// The callback that configures the tags of the file. + /// The duration of the audio of the file, in milliseconds. + public static void CreateTaggedWav(string path, Action configureTags, int durationMs = 200) + { + WriteFile(path, BuildWav(durationMs)); + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + configureTags(tagFile); + tagFile.Save(); + } + } + + /// + /// Creates a file whose content is not a recognizable audio container, so that the resilience of the embedded cover extraction can be exercised. + /// + /// The path where the file is written. + public static void CreateUnsupportedFile(string path) + { + WriteFile(path, Encoding.UTF8.GetBytes("This is not an audio file.")); + } + + /// + /// Writes the provided bytes at , creating the containing directory when it does not exist yet. + /// + /// The path where the bytes are written. + /// The bytes of the file. + private static void WriteFile(string path, byte[] contents) + { + string? directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + File.WriteAllBytes(path, contents); + } + + /// + /// Builds the bytes of a minimal, valid PCM WAV file with a single silent audio channel. + /// + /// The duration of the audio of the file, in milliseconds. + /// The bytes of the WAV file. + private static byte[] BuildWav(int durationMs) + { + const int SAMPLE_RATE = 44100; + const short CHANNELS = 1; + const short BITS_PER_SAMPLE = 16; + + int bytesPerSample = BITS_PER_SAMPLE / 8; + int dataSize = SAMPLE_RATE * CHANNELS * bytesPerSample * durationMs / 1000; + + using (MemoryStream memoryStream = new()) + { + using (BinaryWriter writer = new(memoryStream)) + { + writer.Write(Encoding.ASCII.GetBytes("RIFF")); + writer.Write(36 + dataSize); + writer.Write(Encoding.ASCII.GetBytes("WAVE")); + writer.Write(Encoding.ASCII.GetBytes("fmt ")); + writer.Write(16); + writer.Write((short)1); + writer.Write(CHANNELS); + writer.Write(SAMPLE_RATE); + writer.Write(SAMPLE_RATE * CHANNELS * bytesPerSample); + writer.Write((short)(CHANNELS * bytesPerSample)); + writer.Write(BITS_PER_SAMPLE); + writer.Write(Encoding.ASCII.GetBytes("data")); + writer.Write(dataSize); + writer.Write(new byte[dataSize]); + } + return memoryStream.ToArray(); + } + } +} diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestImageFileFactory.cs b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestImageFileFactory.cs new file mode 100644 index 00000000..4076b5b3 --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestImageFileFactory.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; + +/// +/// Creates image files of the formats a local music library stores next to its tracks, so that artwork scanning can be exercised against real files. +/// Each file carries the magic bytes of its format, mirroring the images a music library keeps in the folders of its artists and albums. +/// +[ExcludeFromCodeCoverage] +public static class TestImageFileFactory +{ + /// + /// Creates a JPEG image file at the provided path. + /// + /// The path where the image is written. + public static void CreateJpeg(string path) + { + WriteFile(path, [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xFF, 0xD9]); + } + + /// + /// Creates a PNG image file at the provided path. + /// + /// The path where the image is written. + public static void CreatePng(string path) + { + WriteFile(path, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52]); + } + + /// + /// Creates a WebP image file at the provided path. + /// + /// The path where the image is written. + public static void CreateWebp(string path) + { + WriteFile(path, [.. Encoding.ASCII.GetBytes("RIFF"), 0x00, 0x00, 0x00, 0x00, .. Encoding.ASCII.GetBytes("WEBP")]); + } + + /// + /// Creates a BMP image file at the provided path. + /// + /// The path where the image is written. + public static void CreateBmp(string path) + { + WriteFile(path, [0x42, 0x4D, 0x00, 0x00, 0x00, 0x00]); + } + + /// + /// Creates a GIF image file at the provided path. + /// + /// The path where the image is written. + public static void CreateGif(string path) + { + WriteFile(path, [.. Encoding.ASCII.GetBytes("GIF89a")]); + } + + /// + /// Creates a TIFF image file at the provided path. + /// + /// The path where the image is written. + public static void CreateTiff(string path) + { + WriteFile(path, [0x49, 0x49, 0x2A, 0x00]); + } + + /// + /// Creates a file whose content is not an image, so that the exclusion of non image files can be exercised. + /// + /// The path where the file is written. + public static void CreateTextFile(string path) + { + WriteFile(path, Encoding.UTF8.GetBytes("This is not an image.")); + } + + /// + /// Writes the provided bytes at , creating the containing directory when it does not exist yet. + /// + /// The path where the bytes are written. + /// The bytes of the file. + private static void WriteFile(string path, byte[] contents) + { + string? directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + File.WriteAllBytes(path, contents); + } +} diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj new file mode 100644 index 00000000..36254ec4 --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + false + false + false + + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..7301273e --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.LocalMusicArtwork.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.LocalMusicArtwork.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3401EC09-8D4F-4E45-9F40-62FEA3C81373")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.IntegrationTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs new file mode 100644 index 00000000..bf3e9d50 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzAliasResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The name of the alias. + /// Whether the name should be included, or forced to . + /// Optional. The sort name of the alias. + /// Whether the sort name should be included, or forced to . + /// Optional. The type of the alias. + /// Whether the type should be included, or forced to . + /// Optional. The locale the alias is used in. + /// Whether the locale should be included, or forced to . + /// Optional. Whether this is the primary alias. + /// Whether the primary flag should be included, or forced to . + /// Optional. The begin date of the alias. + /// Whether the begin date should be included, or forced to . + /// Optional. The end date of the alias. + /// Whether the end date should be included, or forced to . + /// Optional. Whether the alias has ended. + /// Whether the ended flag should be included, or forced to . + /// A configured instance. + public MusicBrainzAliasResponse Create( + string? name = null, + bool includeName = true, + string? sortName = null, + bool includeSortName = true, + string? type = null, + bool includeType = true, + string? locale = null, + bool includeLocale = true, + bool? isPrimary = null, + bool includePrimary = true, + string? begin = null, + bool includeBegin = true, + string? end = null, + bool includeEnd = true, + bool? isEnded = null, + bool includeEnded = true) + { + return new MusicBrainzAliasResponse + { + Name = includeName ? name ?? _faker.Name.FullName() : null, + SortName = includeSortName ? sortName ?? _faker.Name.FullName() : null, + Type = includeType ? type ?? _faker.PickRandom("Artist name", "Legal name") : null, + Locale = includeLocale ? locale ?? _faker.PickRandom("en", "de", "fr") : null, + IsPrimary = includePrimary ? isPrimary ?? _faker.Random.Bool() : null, + Begin = includeBegin ? begin ?? _faker.Date.Past(50).ToString("yyyy-MM-dd") : null, + End = includeEnd ? end ?? _faker.Date.Past(5).ToString("yyyy-MM-dd") : null, + IsEnded = includeEnded ? isEnded ?? _faker.Random.Bool() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs new file mode 100644 index 00000000..865b2068 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzAreaResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the area. + /// Whether the identifier should be included, or forced to . + /// Optional. The name of the area. + /// Whether the name should be included, or forced to . + /// Optional. The sort name of the area. + /// Whether the sort name should be included, or forced to . + /// Optional. The disambiguation comment of the area. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The MusicBrainz type of the area. + /// Whether the type should be included, or forced to . + /// Optional. The ISO 3166-1 codes of the area. + /// Optional. The ISO 3166-2 codes of the area. + /// A configured instance. + public MusicBrainzAreaResponse Create( + string? id = null, + bool includeId = true, + string? name = null, + bool includeName = true, + string? sortName = null, + bool includeSortName = true, + string? disambiguation = null, + bool includeDisambiguation = true, + string? type = null, + bool includeType = true, + List? iso3166Part1Codes = null, + List? iso3166Part2Codes = null) + { + return new MusicBrainzAreaResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Name = includeName ? name ?? _faker.Address.Country() : null, + SortName = includeSortName ? sortName ?? _faker.Address.Country() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Type = includeType ? type ?? _faker.PickRandom("Country", "City", "Area") : null, + Iso3166Part1Codes = iso3166Part1Codes ?? [_faker.Address.CountryCode()], + Iso3166Part2Codes = iso3166Part2Codes ?? [_faker.Random.String2(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs new file mode 100644 index 00000000..a813a61b --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzArtistCreditResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The credited name of the artist. + /// Whether the name should be included, or forced to . + /// Optional. The join phrase that follows the credit. + /// Whether the join phrase should be included, or forced to . + /// Optional. The artist the credit refers to. + /// Whether the artist should be included, or forced to . + /// A configured instance. + public MusicBrainzArtistCreditResponse Create( + string? name = null, + bool includeName = true, + string? joinPhrase = null, + bool includeJoinPhrase = true, + MusicBrainzArtistResponse? artist = null, + bool includeArtist = true) + { + string? resolvedName = includeName ? name ?? _faker.Name.FullName() : null; + return new MusicBrainzArtistCreditResponse + { + Name = resolvedName, + JoinPhrase = includeJoinPhrase ? joinPhrase ?? _faker.PickRandom(" & ", " feat. ", ", ") : null, + Artist = includeArtist ? artist ?? _musicBrainzArtistResponseFixture.Create(name: resolvedName) : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs new file mode 100644 index 00000000..aac8125e --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzArtistResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new(); + private readonly MusicBrainzAliasResponseFixture _musicBrainzAliasResponseFixture = new(); + private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzLifeSpanResponseFixture _musicBrainzLifeSpanResponseFixture = new(); + private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the artist. + /// Whether the identifier should be included, or forced to . + /// Optional. The name of the artist. + /// Whether the name should be included, or forced to . + /// Optional. The sort name of the artist. + /// Whether the sort name should be included, or forced to . + /// Optional. The disambiguation comment of the artist. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The MusicBrainz type of the artist. + /// Whether the type should be included, or forced to . + /// Optional. The gender of the artist. + /// Whether the gender should be included, or forced to . + /// Optional. The ISO 3166-1 alpha-2 code of the country of the artist. + /// Whether the country should be included, or forced to . + /// Optional. The area the artist is primarily identified with. + /// Whether the area should be included, or forced to . + /// Optional. The area the artist began in. + /// Whether the begin area should be included, or forced to . + /// Optional. The area the artist ended in. + /// Whether the end area should be included, or forced to . + /// Optional. The life span of the artist. + /// Whether the life span should be included, or forced to . + /// Optional. The ISNI codes of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The alternative names of the artist. + /// Optional. The tags of the artist. + /// Optional. The genres of the artist. + /// Optional. The relationships of the artist to other entities. + /// Optional. The aggregated rating of the artist. + /// Whether the rating should be included, or forced to . + /// A configured instance. + public MusicBrainzArtistResponse Create( + string? id = null, + bool includeId = true, + string? name = null, + bool includeName = true, + string? sortName = null, + bool includeSortName = true, + string? disambiguation = null, + bool includeDisambiguation = true, + string? type = null, + bool includeType = true, + string? gender = null, + bool includeGender = true, + string? country = null, + bool includeCountry = true, + MusicBrainzAreaResponse? area = null, + bool includeArea = false, + MusicBrainzAreaResponse? beginArea = null, + bool includeBeginArea = false, + MusicBrainzAreaResponse? endArea = null, + bool includeEndArea = false, + MusicBrainzLifeSpanResponse? lifeSpan = null, + bool includeLifeSpan = false, + List? isnis = null, + List? ipis = null, + List? aliases = null, + List? tags = null, + List? genres = null, + List? relations = null, + MusicBrainzRatingResponse? rating = null, + bool includeRating = false) + { + return new MusicBrainzArtistResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Name = includeName ? name ?? _faker.Name.FullName() : null, + SortName = includeSortName ? sortName ?? _faker.Name.FullName() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Type = includeType ? type ?? _faker.PickRandom("Person", "Group", "Orchestra") : null, + Gender = includeGender ? gender ?? _faker.PickRandom("Male", "Female") : null, + Country = includeCountry ? country ?? _faker.Address.CountryCode() : null, + Area = includeArea ? area ?? _musicBrainzAreaResponseFixture.Create() : null, + BeginArea = includeBeginArea ? beginArea ?? _musicBrainzAreaResponseFixture.Create() : null, + EndArea = includeEndArea ? endArea ?? _musicBrainzAreaResponseFixture.Create() : null, + LifeSpan = includeLifeSpan ? lifeSpan ?? _musicBrainzLifeSpanResponseFixture.Create() : null, + Isnis = isnis ?? [_faker.Random.String2(16, "0123456789")], + Ipis = ipis ?? [_faker.Random.String2(11, "0123456789")], + Aliases = aliases ?? [.. _musicBrainzAliasResponseFixture.CreateMany(2)], + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)], + Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs new file mode 100644 index 00000000..41612d35 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzArtistSearchResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The total number of matching artists. + /// Optional. The offset of the returned artists. + /// Optional. The matching artists. + /// A configured instance. + public MusicBrainzArtistSearchResponse Create( + int? count = null, + int? offset = null, + List? artists = null) + { + List resolvedArtists = artists ?? [.. _musicBrainzArtistResponseFixture.CreateMany(2)]; + return new MusicBrainzArtistSearchResponse + { + Count = count ?? resolvedArtists.Count, + Offset = offset ?? _faker.Random.Int(0, 100), + Artists = resolvedArtists + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs new file mode 100644 index 00000000..d6e16399 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzLabelInfoResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzLabelResponseFixture _musicBrainzLabelResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The catalog number assigned by the label. + /// Whether the catalog number should be included, or forced to . + /// Optional. The label that issued the release. + /// Whether the label should be included, or forced to . + /// A configured instance. + public MusicBrainzLabelInfoResponse Create( + string? catalogNumber = null, + bool includeCatalogNumber = true, + MusicBrainzLabelResponse? label = null, + bool includeLabel = true) + { + return new MusicBrainzLabelInfoResponse + { + CatalogNumber = includeCatalogNumber ? catalogNumber ?? _faker.Random.AlphaNumeric(8).ToUpperInvariant() : null, + Label = includeLabel ? label ?? _musicBrainzLabelResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs new file mode 100644 index 00000000..438c0390 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzLabelResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the label. + /// Whether the identifier should be included, or forced to . + /// Optional. The name of the label. + /// Whether the name should be included, or forced to . + /// Optional. The disambiguation comment of the label. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The label code of the label. + /// Whether the label code should be included, or forced to . + /// A configured instance. + public MusicBrainzLabelResponse Create( + string? id = null, + bool includeId = true, + string? name = null, + bool includeName = true, + string? disambiguation = null, + bool includeDisambiguation = true, + int? labelCode = null, + bool includeLabelCode = true) + { + return new MusicBrainzLabelResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Name = includeName ? name ?? _faker.Company.CompanyName() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + LabelCode = includeLabelCode ? labelCode ?? _faker.Random.Int(1, 9999) : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs new file mode 100644 index 00000000..b5bb5346 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzLifeSpanResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The begin date of the life span. + /// Whether the begin date should be included, or forced to . + /// Optional. The end date of the life span. + /// Whether the end date should be included, or forced to . + /// Optional. Whether the life span has ended. + /// Whether the ended flag should be included, or forced to . + /// A configured instance. + public MusicBrainzLifeSpanResponse Create( + string? begin = null, + bool includeBegin = true, + string? end = null, + bool includeEnd = true, + bool? isEnded = null, + bool includeEnded = true) + { + return new MusicBrainzLifeSpanResponse + { + Begin = includeBegin ? begin ?? _faker.Date.Past(60).ToString("yyyy-MM-dd") : null, + End = includeEnd ? end ?? _faker.Date.Past(5).ToString("yyyy-MM-dd") : null, + IsEnded = includeEnded ? isEnded ?? _faker.Random.Bool() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs new file mode 100644 index 00000000..55ca6bf6 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzMediumResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzTrackResponseFixture _musicBrainzTrackResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The position of the medium within its release. + /// Optional. The title of the medium. + /// Whether the title should be included, or forced to . + /// Optional. The format of the medium. + /// Whether the format should be included, or forced to . + /// Optional. The number of tracks of the medium. + /// Optional. The tracks of the medium. + /// A configured instance. + public MusicBrainzMediumResponse Create( + int? position = null, + string? title = null, + bool includeTitle = true, + string? format = null, + bool includeFormat = true, + int? trackCount = null, + List? tracks = null) + { + List resolvedTracks = tracks ?? [.. _musicBrainzTrackResponseFixture.CreateMany(2)]; + return new MusicBrainzMediumResponse + { + Position = position ?? _faker.Random.Int(1, 4), + Title = includeTitle ? title ?? _faker.Lorem.Sentence(2) : null, + Format = includeFormat ? format ?? _faker.PickRandom("CD", "Vinyl", "Digital Media") : null, + TrackCount = trackCount ?? resolvedTracks.Count, + Tracks = resolvedTracks + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs new file mode 100644 index 00000000..4dd684ff --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRatingResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The average rating value. + /// Whether the value should be included, or forced to . + /// Optional. The number of votes that contributed to the rating. + /// Whether the votes count should be included, or forced to . + /// A configured instance. + public MusicBrainzRatingResponse Create( + decimal? value = null, + bool includeValue = true, + int? votesCount = null, + bool includeVotesCount = true) + { + return new MusicBrainzRatingResponse + { + Value = includeValue ? value ?? _faker.Random.Decimal(1m, 5m) : null, + VotesCount = includeVotesCount ? votesCount ?? _faker.Random.Int(1, 500) : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs new file mode 100644 index 00000000..5556e4e5 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRecordingListResponseFixture +{ + private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The recordings that carry the looked up ISRC. + /// A configured instance. + public MusicBrainzRecordingListResponse Create(List? recordings = null) + { + return new MusicBrainzRecordingListResponse + { + Recordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs new file mode 100644 index 00000000..07a2e22a --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// The releases of the recording default to an empty list, because a recording embedded in a release does not carry them. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRecordingResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new(); + private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the recording. + /// Whether the identifier should be included, or forced to . + /// Optional. The title of the recording. + /// Whether the title should be included, or forced to . + /// Optional. The disambiguation comment of the recording. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The length of the recording in milliseconds. + /// Whether the length should be included, or forced to . + /// Optional. Whether the recording is a video recording. + /// Whether the video flag should be included, or forced to . + /// Optional. The date the recording was first released. + /// Whether the first release date should be included, or forced to . + /// Optional. The artist credit of the recording. + /// Optional. The ISRCs of the recording. + /// Optional. The releases the recording appears on. + /// Optional. The tags of the recording. + /// Optional. The genres of the recording. + /// Optional. The relationships of the recording to other entities. + /// Optional. The aggregated rating of the recording. + /// Whether the rating should be included, or forced to . + /// A configured instance. + public MusicBrainzRecordingResponse Create( + string? id = null, + bool includeId = true, + string? title = null, + bool includeTitle = true, + string? disambiguation = null, + bool includeDisambiguation = true, + long? length = null, + bool includeLength = true, + bool? isVideo = null, + bool includeVideo = true, + string? firstReleaseDate = null, + bool includeFirstReleaseDate = true, + List? artistCredit = null, + List? isrcs = null, + List? releases = null, + List? tags = null, + List? genres = null, + List? relations = null, + MusicBrainzRatingResponse? rating = null, + bool includeRating = false) + { + return new MusicBrainzRecordingResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Length = includeLength ? length ?? _faker.Random.Long(30_000, 600_000) : null, + IsVideo = includeVideo ? isVideo ?? _faker.Random.Bool() : null, + FirstReleaseDate = includeFirstReleaseDate ? firstReleaseDate ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null, + ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)], + Isrcs = isrcs ?? [$"US{_faker.Random.AlphaNumeric(10).ToUpperInvariant()}"], + Releases = releases ?? [], + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)], + Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs new file mode 100644 index 00000000..a2f2750f --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRecordingSearchResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The total number of matching recordings. + /// Optional. The offset of the returned recordings. + /// Optional. The matching recordings. + /// A configured instance. + public MusicBrainzRecordingSearchResponse Create( + int? count = null, + int? offset = null, + List? recordings = null) + { + List resolvedRecordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)]; + return new MusicBrainzRecordingSearchResponse + { + Count = count ?? resolvedRecordings.Count, + Offset = offset ?? _faker.Random.Int(0, 100), + Recordings = resolvedRecordings + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs new file mode 100644 index 00000000..b8e7afea --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// The nested artist, work and url targets are optional, because a relation usually targets only one of them. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRelationResponseFixture +{ + private readonly Faker _faker = new(); + + // The artist and work fixtures each compose a relation fixture of their own, so holding them eagerly here would recurse forever; they are + // therefore created on first use. The URL fixture has no such dependency, so it is held directly. + private readonly Lazy _musicBrainzArtistResponseFixture = new(() => new MusicBrainzArtistResponseFixture()); + private readonly Lazy _musicBrainzWorkResponseFixture = new(() => new MusicBrainzWorkResponseFixture()); + private readonly MusicBrainzUrlResponseFixture _musicBrainzUrlResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The type of the relationship. + /// Whether the type should be included, or forced to . + /// Optional. The MusicBrainz identifier of the type of the relationship. + /// Whether the type identifier should be included, or forced to . + /// Optional. The direction of the relationship. + /// Whether the direction should be included, or forced to . + /// Optional. The type of the entity the relationship targets. + /// Whether the target type should be included, or forced to . + /// Optional. The artist the relationship targets. + /// Whether the artist should be included, or forced to . + /// Optional. The work the relationship targets. + /// Whether the work should be included, or forced to . + /// Optional. The URL the relationship targets. + /// Whether the URL should be included, or forced to . + /// Optional. The attributes of the relationship. + /// A configured instance. + public MusicBrainzRelationResponse Create( + string? type = null, + bool includeType = true, + string? typeId = null, + bool includeTypeId = true, + string? direction = null, + bool includeDirection = true, + string? targetType = null, + bool includeTargetType = true, + MusicBrainzArtistResponse? artist = null, + bool includeArtist = false, + MusicBrainzWorkResponse? work = null, + bool includeWork = false, + MusicBrainzUrlResponse? url = null, + bool includeUrl = false, + List? attributes = null) + { + return new MusicBrainzRelationResponse + { + Type = includeType ? type ?? _faker.PickRandom("producer", "composer", "performer") : null, + TypeId = includeTypeId ? typeId ?? Guid.NewGuid().ToString() : null, + Direction = includeDirection ? direction ?? "backward" : null, + TargetType = includeTargetType ? targetType ?? "artist" : null, + Artist = includeArtist ? artist ?? _musicBrainzArtistResponseFixture.Value.Create() : null, + Work = includeWork ? work ?? _musicBrainzWorkResponseFixture.Value.Create() : null, + Url = includeUrl ? url ?? _musicBrainzUrlResponseFixture.Create() : null, + Attributes = attributes ?? [] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs new file mode 100644 index 00000000..490996ec --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseBrowseResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzReleaseResponseFixture _musicBrainzReleaseResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The releases returned by the browse request. + /// Optional. The total number of releases linked to the browsed entity. + /// Optional. The offset of the returned releases. + /// A configured instance. + public MusicBrainzReleaseBrowseResponse Create( + List? releases = null, + int? releaseCount = null, + int? releaseOffset = null) + { + List resolvedReleases = releases ?? [.. _musicBrainzReleaseResponseFixture.CreateMany(2)]; + return new MusicBrainzReleaseBrowseResponse + { + Releases = resolvedReleases, + ReleaseCount = releaseCount ?? resolvedReleases.Count, + ReleaseOffset = releaseOffset ?? _faker.Random.Int(0, 100) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs new file mode 100644 index 00000000..3817e8b9 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseEventResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The date of the release event. + /// Whether the date should be included, or forced to . + /// Optional. The area of the release event. + /// Whether the area should be included, or forced to . + /// A configured instance. + public MusicBrainzReleaseEventResponse Create( + string? date = null, + bool includeDate = true, + MusicBrainzAreaResponse? area = null, + bool includeArea = true) + { + return new MusicBrainzReleaseEventResponse + { + Date = includeDate ? date ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null, + Area = includeArea ? area ?? _musicBrainzAreaResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs new file mode 100644 index 00000000..30cf9ff3 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// The releases of the release group default to an empty list, because they are only returned by a dedicated browse request. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseGroupResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the release group. + /// Whether the identifier should be included, or forced to . + /// Optional. The title of the release group. + /// Whether the title should be included, or forced to . + /// Optional. The disambiguation comment of the release group. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The primary type of the release group. + /// Whether the primary type should be included, or forced to . + /// Optional. The secondary types of the release group. + /// Optional. The date the release group was first released. + /// Whether the first release date should be included, or forced to . + /// Optional. The artist credit of the release group. + /// Optional. The releases of the release group. + /// Optional. The tags of the release group. + /// Optional. The genres of the release group. + /// Optional. The aggregated rating of the release group. + /// Whether the rating should be included, or forced to . + /// A configured instance. + public MusicBrainzReleaseGroupResponse Create( + string? id = null, + bool includeId = true, + string? title = null, + bool includeTitle = true, + string? disambiguation = null, + bool includeDisambiguation = true, + string? primaryType = null, + bool includePrimaryType = true, + List? secondaryTypes = null, + string? firstReleaseDate = null, + bool includeFirstReleaseDate = true, + List? artistCredit = null, + List? releases = null, + List? tags = null, + List? genres = null, + MusicBrainzRatingResponse? rating = null, + bool includeRating = false) + { + return new MusicBrainzReleaseGroupResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Title = includeTitle ? title ?? _faker.Commerce.ProductName() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + PrimaryType = includePrimaryType ? primaryType ?? _faker.PickRandom("Album", "Single", "EP") : null, + SecondaryTypes = secondaryTypes ?? [], + FirstReleaseDate = includeFirstReleaseDate ? firstReleaseDate ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null, + ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)], + Releases = releases ?? [], + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs new file mode 100644 index 00000000..cb1afb9a --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseGroupSearchResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The total number of matching release groups. + /// Optional. The offset of the returned release groups. + /// Optional. The matching release groups. + /// A configured instance. + public MusicBrainzReleaseGroupSearchResponse Create( + int? count = null, + int? offset = null, + List? releaseGroups = null) + { + List resolvedReleaseGroups = releaseGroups ?? [.. _musicBrainzReleaseGroupResponseFixture.CreateMany(2)]; + return new MusicBrainzReleaseGroupSearchResponse + { + Count = count ?? resolvedReleaseGroups.Count, + Offset = offset ?? _faker.Random.Int(0, 100), + ReleaseGroups = resolvedReleaseGroups + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs new file mode 100644 index 00000000..11da2c2f --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new(); + private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new(); + private readonly MusicBrainzLabelInfoResponseFixture _musicBrainzLabelInfoResponseFixture = new(); + private readonly MusicBrainzMediumResponseFixture _musicBrainzMediumResponseFixture = new(); + private readonly MusicBrainzReleaseEventResponseFixture _musicBrainzReleaseEventResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzTextRepresentationResponseFixture _musicBrainzTextRepresentationResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the release. + /// Whether the identifier should be included, or forced to . + /// Optional. The title of the release. + /// Whether the title should be included, or forced to . + /// Optional. The disambiguation comment of the release. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The status of the release. + /// Whether the status should be included, or forced to . + /// Optional. The date the release was issued. + /// Whether the date should be included, or forced to . + /// Optional. The ISO 3166-1 alpha-2 code of the country the release was issued in. + /// Whether the country should be included, or forced to . + /// Optional. The release events of the release. + /// Optional. The barcode of the release. + /// Whether the barcode should be included, or forced to . + /// Optional. The outermost packaging of the release. + /// Whether the packaging should be included, or forced to . + /// Optional. The language and script of the titles of the release. + /// Whether the text representation should be included, or forced to . + /// Optional. The artist credit of the release. + /// Optional. The release group the release belongs to. + /// Whether the release group should be included, or forced to . + /// Optional. The label information of the release. + /// Optional. The media of the release. + /// Optional. The ASIN of the release. + /// Whether the ASIN should be included, or forced to . + /// Optional. The tags of the release. + /// Optional. The genres of the release. + /// Optional. The relationships of the release to other entities. + /// A configured instance. + public MusicBrainzReleaseResponse Create( + string? id = null, + bool includeId = true, + string? title = null, + bool includeTitle = true, + string? disambiguation = null, + bool includeDisambiguation = true, + string? status = null, + bool includeStatus = true, + string? date = null, + bool includeDate = true, + string? country = null, + bool includeCountry = true, + List? releaseEvents = null, + string? barcode = null, + bool includeBarcode = true, + string? packaging = null, + bool includePackaging = true, + MusicBrainzTextRepresentationResponse? textRepresentation = null, + bool includeTextRepresentation = true, + List? artistCredit = null, + MusicBrainzReleaseGroupResponse? releaseGroup = null, + bool includeReleaseGroup = true, + List? labelInfo = null, + List? media = null, + string? asin = null, + bool includeAsin = true, + List? tags = null, + List? genres = null, + List? relations = null) + { + return new MusicBrainzReleaseResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Title = includeTitle ? title ?? _faker.Commerce.ProductName() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Status = includeStatus ? status ?? _faker.PickRandom("Official", "Promotion", "Bootleg") : null, + Date = includeDate ? date ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null, + Country = includeCountry ? country ?? _faker.Address.CountryCode() : null, + ReleaseEvents = releaseEvents ?? [.. _musicBrainzReleaseEventResponseFixture.CreateMany(1)], + Barcode = includeBarcode ? barcode ?? _faker.Random.AlphaNumeric(12) : null, + Packaging = includePackaging ? packaging ?? _faker.PickRandom("Jewel Case", "Digipak") : null, + TextRepresentation = includeTextRepresentation ? textRepresentation ?? _musicBrainzTextRepresentationResponseFixture.Create() : null, + ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)], + ReleaseGroup = includeReleaseGroup ? releaseGroup ?? _musicBrainzReleaseGroupResponseFixture.Create() : null, + LabelInfo = labelInfo ?? [.. _musicBrainzLabelInfoResponseFixture.CreateMany(1)], + Media = media ?? [.. _musicBrainzMediumResponseFixture.CreateMany(1)], + Asin = includeAsin ? asin ?? _faker.Random.AlphaNumeric(10) : null, + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Relations = relations ?? [] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs new file mode 100644 index 00000000..d3eb53cc --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzTagResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of a genre tag. + /// Whether the identifier should be included, or forced to . + /// Optional. The name of the tag. + /// Whether the name should be included, or forced to . + /// Optional. The disambiguation comment of a genre tag. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The number of votes the tag received. + /// A configured instance. + public MusicBrainzTagResponse Create( + string? id = null, + bool includeId = true, + string? name = null, + bool includeName = true, + string? disambiguation = null, + bool includeDisambiguation = true, + int? count = null) + { + return new MusicBrainzTagResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Name = includeName ? name ?? _faker.Lorem.Word() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Count = count ?? _faker.Random.Int(0, 100) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs new file mode 100644 index 00000000..68787c3b --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzTextRepresentationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The ISO 639-3 language code of the release. + /// Whether the language should be included, or forced to . + /// Optional. The ISO 15924 script code of the release. + /// Whether the script should be included, or forced to . + /// A configured instance. + public MusicBrainzTextRepresentationResponse Create( + string? language = null, + bool includeLanguage = true, + string? script = null, + bool includeScript = true) + { + return new MusicBrainzTextRepresentationResponse + { + Language = includeLanguage ? language ?? _faker.PickRandom("eng", "deu", "fra") : null, + Script = includeScript ? script ?? _faker.PickRandom("Latn", "Cyrl", "Arab") : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs new file mode 100644 index 00000000..745a2db1 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzTrackResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the track. + /// Whether the identifier should be included, or forced to . + /// Optional. The track number, as displayed on the medium. + /// Whether the number should be included, or forced to . + /// Optional. The position of the track within its medium. + /// Optional. The title of the track. + /// Whether the title should be included, or forced to . + /// Optional. The length of the track in milliseconds. + /// Whether the length should be included, or forced to . + /// Optional. The recording the track is a performance of. + /// Whether the recording should be included, or forced to . + /// A configured instance. + public MusicBrainzTrackResponse Create( + string? id = null, + bool includeId = true, + string? number = null, + bool includeNumber = true, + int? position = null, + string? title = null, + bool includeTitle = true, + long? length = null, + bool includeLength = true, + MusicBrainzRecordingResponse? recording = null, + bool includeRecording = true) + { + int resolvedPosition = position ?? _faker.Random.Int(1, 30); + string? resolvedTitle = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null; + return new MusicBrainzTrackResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Number = includeNumber ? number ?? resolvedPosition.ToString() : null, + Position = resolvedPosition, + Title = resolvedTitle, + Length = includeLength ? length ?? _faker.Random.Long(30_000, 600_000) : null, + Recording = includeRecording ? recording ?? _musicBrainzRecordingResponseFixture.Create(title: resolvedTitle) : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs new file mode 100644 index 00000000..08602a9b --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzUrlResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the URL. + /// Whether the identifier should be included, or forced to . + /// Optional. The resource the URL points to. + /// Whether the resource should be included, or forced to . + /// A configured instance. + public MusicBrainzUrlResponse Create( + string? id = null, + bool includeId = true, + string? resource = null, + bool includeResource = true) + { + return new MusicBrainzUrlResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Resource = includeResource ? resource ?? _faker.Internet.Url() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs new file mode 100644 index 00000000..09311696 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzWorkResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the work. + /// Whether the identifier should be included, or forced to . + /// Optional. The title of the work. + /// Whether the title should be included, or forced to . + /// Optional. The MusicBrainz type of the work. + /// Whether the type should be included, or forced to . + /// Optional. The disambiguation comment of the work. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The languages of the work. + /// Optional. The ISWCs of the work. + /// Optional. The relationships of the work to other entities. + /// Optional. The tags of the work. + /// Optional. The genres of the work. + /// A configured instance. + public MusicBrainzWorkResponse Create( + string? id = null, + bool includeId = true, + string? title = null, + bool includeTitle = true, + string? type = null, + bool includeType = true, + string? disambiguation = null, + bool includeDisambiguation = true, + List? languages = null, + List? iswcs = null, + List? relations = null, + List? tags = null, + List? genres = null) + { + return new MusicBrainzWorkResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null, + Type = includeType ? type ?? _faker.PickRandom("Song", "Aria", "Symphony") : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Languages = languages ?? [_faker.PickRandom("eng", "deu", "fra")], + Iswcs = iswcs ?? [$"T-{_faker.Random.Int(100, 999)}.{_faker.Random.Int(100, 999)}.{_faker.Random.Int(100, 999)}-{_faker.Random.Int(1, 9)}"], + Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)], + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs new file mode 100644 index 00000000..c1b2abae --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The base URL of the MusicBrainz web service. + /// Optional. Whether the base URL may point at a private or local host. + /// Optional. The user agent sent with every request. + /// Optional. The contact email sent to the MusicBrainz API. + /// Whether the contact email should be included, or forced to . + /// Optional. The maximum number of results returned by a single search. + /// Optional. The maximum number of releases fetched for a single release group. + /// Optional. The minimum interval between consecutive requests. + /// A configured instance. + public MusicBrainzSettingsDto Create( + string? baseUrl = null, + bool? doesAllowPrivateBaseUrl = null, + string? userAgent = null, + string? contactEmail = null, + bool includeContactEmail = true, + int? searchResultLimit = null, + int? releaseLookupLimit = null, + TimeSpan? minimumRequestInterval = null) + { + return new MusicBrainzSettingsDto + { + BaseUrl = baseUrl ?? _faker.Internet.Url(), + DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrl ?? _faker.Random.Bool(), + UserAgent = userAgent ?? $"Lumina-MusicBrainz/{_faker.Random.Int(1, 9)}.{_faker.Random.Int(0, 9)}", + ContactEmail = includeContactEmail ? contactEmail ?? _faker.Internet.Email() : null, + SearchResultLimit = searchResultLimit ?? _faker.Random.Int(1, 100), + ReleaseLookupLimit = releaseLookupLimit ?? _faker.Random.Int(1, 100), + MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromSeconds(_faker.Random.Double(0, 5)) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj new file mode 100644 index 00000000..47ab1ad4 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + false + false + false + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..6e22c2f7 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,22 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.MusicBrainz.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.MusicBrainz.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM. +[assembly: Guid("C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.SecurityTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.IntegrationTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingsResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingsResponseFixture.cs index f55a8e5f..8684a510 100644 --- a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingsResponseFixture.cs +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingsResponseFixture.cs @@ -11,7 +11,7 @@ namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; [ExcludeFromCodeCoverage] internal class OpenLibraryRatingsResponseFixture { - private readonly OpenLibraryRatingSummaryResponseFixture _ratingSummaryResponseFixture = new(); + private readonly OpenLibraryRatingSummaryResponseFixture _openLibraryRatingSummaryResponseFixture = new(); /// /// Creates a random valid . @@ -22,7 +22,7 @@ internal class OpenLibraryRatingsResponseFixture { return new OpenLibraryRatingsResponse { - Summary = summary ?? _ratingSummaryResponseFixture.Create() + Summary = summary ?? _openLibraryRatingSummaryResponseFixture.Create() }; } } diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponseFixture.cs index fb011624..8ba3fbb1 100644 --- a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponseFixture.cs +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponseFixture.cs @@ -13,7 +13,7 @@ namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; internal class OpenLibraryWorkAuthorResponseFixture { private readonly Faker _faker = new(); - private readonly OpenLibraryKeyReferenceResponseFixture _keyReferenceResponseFixture = new(); + private readonly OpenLibraryKeyReferenceResponseFixture _openLibraryKeyReferenceResponseFixture = new(); /// /// Creates a random valid . @@ -27,7 +27,7 @@ internal class OpenLibraryWorkAuthorResponseFixture { return new OpenLibraryWorkAuthorResponse { - Author = author ?? _keyReferenceResponseFixture.Create(key: $"/authors/OL{_faker.Random.Number(1000, 9999)}A"), + Author = author ?? _openLibraryKeyReferenceResponseFixture.Create(key: $"/authors/OL{_faker.Random.Number(1000, 9999)}A"), Key = key }; } diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/DTO/Settings/OpenLibrarySettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/DTO/Settings/OpenLibrarySettingsDtoFixture.cs index 9392328e..d71aac4d 100644 --- a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/DTO/Settings/OpenLibrarySettingsDtoFixture.cs +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/DTO/Settings/OpenLibrarySettingsDtoFixture.cs @@ -23,21 +23,34 @@ internal class OpenLibrarySettingsDtoFixture /// Optional. The maximum number of search results. /// Optional. The maximum number of editions fetched per work. /// Optional. The minimum interval between consecutive requests. + /// Whether the user agent should be included, or left at its default value. + /// Whether the search result limit should be included, or left at its default value. + /// Whether the work edition limit should be included, or left at its default value. + /// Whether the minimum request interval should be included, or left at its default value. /// The created . public OpenLibrarySettingsDto Create( string? userAgent = null, string? contactEmail = null, int? searchResultLimit = null, int? workEditionLimit = null, - TimeSpan? minimumRequestInterval = null) + TimeSpan? minimumRequestInterval = null, + bool includeUserAgent = true, + bool includeSearchResultLimit = true, + bool includeWorkEditionLimit = true, + bool includeMinimumRequestInterval = true) { - return new OpenLibrarySettingsDto + OpenLibrarySettingsDto settings = new() { - UserAgent = userAgent ?? _faker.Internet.UserAgent(), - ContactEmail = contactEmail, - SearchResultLimit = searchResultLimit ?? _faker.Random.Number(1, 50), - WorkEditionLimit = workEditionLimit ?? _faker.Random.Number(1, 200), - MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromMilliseconds(_faker.Random.Number(100, 2000)) + ContactEmail = contactEmail }; + if (includeUserAgent) + settings.UserAgent = userAgent ?? _faker.Internet.UserAgent(); + if (includeSearchResultLimit) + settings.SearchResultLimit = searchResultLimit ?? _faker.Random.Number(1, 50); + if (includeWorkEditionLimit) + settings.WorkEditionLimit = workEditionLimit ?? _faker.Random.Number(1, 200); + if (includeMinimumRequestInterval) + settings.MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromMilliseconds(_faker.Random.Number(100, 2000)); + return settings; } } diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Lumina.Plugins.OpenLibrary.Fixtures.csproj b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Lumina.Plugins.OpenLibrary.Fixtures.csproj index 16006591..8d746c3b 100644 --- a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Lumina.Plugins.OpenLibrary.Fixtures.csproj +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Lumina.Plugins.OpenLibrary.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Plugins.Pdf.Fixtures/Lumina.Plugins.Pdf.Fixtures.csproj b/tests/Common/Lumina.Plugins.Pdf.Fixtures/Lumina.Plugins.Pdf.Fixtures.csproj index 5d50d808..fd50ea5e 100644 --- a/tests/Common/Lumina.Plugins.Pdf.Fixtures/Lumina.Plugins.Pdf.Fixtures.csproj +++ b/tests/Common/Lumina.Plugins.Pdf.Fixtures/Lumina.Plugins.Pdf.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Presentation.Api.Fixtures/Lumina.Presentation.Api.Fixtures.csproj b/tests/Common/Lumina.Presentation.Api.Fixtures/Lumina.Presentation.Api.Fixtures.csproj index e91b02df..2ebcd4b3 100644 --- a/tests/Common/Lumina.Presentation.Api.Fixtures/Lumina.Presentation.Api.Fixtures.csproj +++ b/tests/Common/Lumina.Presentation.Api.Fixtures/Lumina.Presentation.Api.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs index 0c21230c..2f35df67 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class PermissionDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs index 855fc922..66363254 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class RoleDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/GenreDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/GenreDtoFixture.cs index db5f4488..1d263f26 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/GenreDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/GenreDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class GenreDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/LanguageInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/LanguageInfoDtoFixture.cs index ab68b3b8..35526dd8 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/LanguageInfoDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/LanguageInfoDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LanguageInfoDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs index fbb0e8e7..0ce812b6 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs @@ -24,20 +24,24 @@ public class ProblemDetailsDtoFixture /// Optional. The HTTP status code generated by the server. /// Optional. A detailed explanation specific to this occurrence of the problem. /// Optional. A URI reference that identifies the specific occurrence of the problem. + /// Whether the problem type should be included, or forced to . + /// Whether the problem detail should be included, or forced to . /// The created . public ProblemDetailsDto Create( string? type = null, string? title = null, int? status = null, string? detail = null, - string? instance = null) + string? instance = null, + bool includeType = true, + bool includeDetail = true) { return new ProblemDetailsDto { - Type = type ?? "https://tools.ietf.org/html/rfc4918#section-11.2", + Type = includeType ? (type ?? "https://tools.ietf.org/html/rfc4918#section-11.2") : null, Title = title ?? _faker.Lorem.Word(), Status = status ?? _faker.Random.Int(400, 599), - Detail = detail ?? _faker.Lorem.Sentence(), + Detail = includeDetail ? (detail ?? _faker.Lorem.Sentence()) : null, Instance = instance }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ReleaseInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ReleaseInfoDtoFixture.cs index b3744d55..d00d01bd 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ReleaseInfoDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ReleaseInfoDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ReleaseInfoDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/TagDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/TagDtoFixture.cs index 4c85476a..11d75a66 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/TagDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/TagDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class TagDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs index fc636ac0..412b7678 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class FileDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs index 513aaae0..277615e0 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class FileSystemTreeNodeDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs index e4c61cb2..caf1efb0 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class FileSystemTypeDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs index 8b65f0bb..ede43fba 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class PathExistsDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs index 99d78637..135aebfb 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class PathSegmentDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs index c96d8615..e0a848a6 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class PathSeparatorDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs index 3bf00678..a8e664d7 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class PathValidDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs index bf1d8f30..4fcd5780 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathPartDefinitionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathPartDefinitionDtoFixture.cs new file mode 100644 index 00000000..57ace7bd --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathPartDefinitionDtoFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartDefinitionDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional kind of the path part. + /// Optional value type captured by the path part. + /// Optional default representation of the path part. + /// Optional value indicating whether the path part is optional by default. + /// A configured instance. + public LibraryPathPartDefinitionDto Create( + string? kind = null, + string? valueType = null, + string? defaultRepresentation = null, + bool? isOptionalByDefault = null) + { + return new LibraryPathPartDefinitionDto + { + Kind = kind ?? _faker.Random.Word(), + ValueType = valueType ?? _faker.Random.Word(), + DefaultRepresentation = defaultRepresentation ?? "{0}", + IsOptionalByDefault = isOptionalByDefault ?? _faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplateCatalogDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplateCatalogDtoFixture.cs new file mode 100644 index 00000000..92963aca --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplateCatalogDtoFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateCatalogDtoFixture +{ + private readonly LibraryPathPartDefinitionDtoFixture _libraryPathPartDefinitionDtoFixture = new(); + private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional path parts that can be used in the path template of the library type. + /// Optional ordered parts of the default path template of the library type. + /// Whether the catalog should carry selectable path parts. When , the parts are forced to an empty collection. + /// Whether the catalog should carry default template parts. When , the default template parts are forced to an empty collection. + /// A configured instance. + public LibraryPathTemplateCatalogDto Create( + List? parts = null, + List? defaultTemplateParts = null, + bool includeParts = true, + bool includeDefaultTemplateParts = true) + { + return new LibraryPathTemplateCatalogDto + { + Parts = includeParts ? (parts ?? _libraryPathPartDefinitionDtoFixture.CreateMany(2)) : [], + DefaultTemplateParts = includeDefaultTemplateParts ? (defaultTemplateParts ?? _libraryPathTemplatePartDtoFixture.CreateMany(2)) : [] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplatePartDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplatePartDtoFixture.cs new file mode 100644 index 00000000..113c2fa0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplatePartDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional kind of the path part. + /// Optional literal text or value mask of the path part. + /// Optional value indicating whether the path part can be absent from the path. + /// A configured instance. + public LibraryPathTemplatePartDto Create( + string? kind = null, + string? representation = null, + bool? isOptional = null) + { + return new LibraryPathTemplatePartDto + { + Kind = kind ?? _faker.Random.Word(), + Representation = representation ?? "{0}", + IsOptional = isOptional ?? _faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs index 8419793d..327bddcd 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryScanJobProgressDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs index 08af8992..8def70c0 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryScanProgressDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs index 8bf4938f..77b8f2f1 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class PaginatedBookLiteDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs index 9a040489..d6c4037e 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ScanLibraryDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs index dc8aee52..60146009 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Bogus; using Lumina.Presentation.Web.Common.DTO.MediaContributors; using Lumina.Presentation.Web.Common.Enums.MediaContributors; using System.Collections.Generic; @@ -10,12 +9,12 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class MediaContributorDtoFixture { - private readonly Faker _faker = new(); + private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new(); /// /// Creates a new instance with randomized test data. @@ -31,11 +30,7 @@ public class MediaContributorDtoFixture { return new MediaContributorDto { - Name = new MediaContributorNameDto - { - DisplayName = displayName ?? _faker.Name.FullName(), - LegalName = legalName ?? _faker.Name.FullName() - }, + Name = _mediaContributorNameDtoFixture.Create(displayName, legalName), Role = role ?? MediaContributorRole.Author }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorNameDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorNameDtoFixture.cs new file mode 100644 index 00000000..9f91549f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorNameDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorNameDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The name by which the contributor is popularly known. + /// Optional. The legal name of the contributor. + /// A configured instance. + public MediaContributorNameDto Create( + string? displayName = null, + string? legalName = null) + { + return new MediaContributorNameDto + { + DisplayName = displayName ?? _faker.Name.FullName(), + LegalName = legalName ?? _faker.Name.FullName() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryArtworkProviderDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryArtworkProviderDtoFixture.cs index 3b423c12..6f98aaa1 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryArtworkProviderDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryArtworkProviderDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryArtworkProviderDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryBookReaderDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryBookReaderDtoFixture.cs index aafc076d..37f31160 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryBookReaderDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryBookReaderDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryBookReaderDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs index 02c24777..634321e6 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class LibraryMetadataProviderDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginDtoFixture.cs index ba291631..736b0282 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class PluginDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs index a09d3974..4f3a50f3 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class PluginSettingsDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingAvailabilityDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingAvailabilityDtoFixture.cs index ca227e96..a269ceec 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingAvailabilityDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingAvailabilityDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Reading; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ReadingAvailabilityDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingManifestDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingManifestDtoFixture.cs index 1f8b2fc4..a089b8c5 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingManifestDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingManifestDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Reading; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ReadingManifestDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingSectionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingSectionDtoFixture.cs index b59ea130..14cc4b2b 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingSectionDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingSectionDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Reading; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ReadingSectionDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingSpineItemDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingSpineItemDtoFixture.cs index d4fda5b8..747363ff 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingSpineItemDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingSpineItemDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Reading; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ReadingSpineItemDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingTocEntryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingTocEntryDtoFixture.cs index 025eef0f..6b0bfcd2 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingTocEntryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Reading/ReadingTocEntryDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Reading; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ReadingTocEntryDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobDtoFixture.cs index a9b88f9f..8b75c681 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ScheduledJobDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobExecutionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobExecutionDtoFixture.cs index 621619c2..193f34f7 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobExecutionDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobExecutionDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ScheduledJobExecutionDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/SchedulerDisplayPreferencesDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/SchedulerDisplayPreferencesDtoFixture.cs index 103b48f2..6b713256 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/SchedulerDisplayPreferencesDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/SchedulerDisplayPreferencesDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class SchedulerDisplayPreferencesDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeFileSystemBrowserConfigurationDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeFileSystemBrowserConfigurationDtoFixture.cs index f84cc8e3..d93642ef 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeFileSystemBrowserConfigurationDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeFileSystemBrowserConfigurationDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemeFileSystemBrowserConfigurationDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeFileSystemBrowserDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeFileSystemBrowserDtoFixture.cs index a73c58d2..c19b3219 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeFileSystemBrowserDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeFileSystemBrowserDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemeFileSystemBrowserDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs index a6265310..e72a9e28 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemeInfoDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs index b2bb7ae1..b367253b 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemeNavMenuDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs index eabcf668..412dbece 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ThemePageDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs index 647af988..22c17d1d 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemePageRenderResultDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs index 9e9717de..a9e2ff3f 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemeRenderDocumentDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs index 8cf8b0bb..c1f9473c 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemeResponseDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs index 71ad89cc..5809a8a6 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemeSettingsResponseDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs index ed45d6f5..c1972755 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ThemeTemplateResponseDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs index e6fb93e8..4aaedbf1 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class UserDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs index 78a2afc9..29004a70 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class UserSettingsDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs index fdc2ba2b..26d0886e 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs @@ -15,7 +15,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class BookDetailsDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs index 49cb5256..c6c79429 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class BookRatingDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDtoFixture.cs index c84c8be0..3d1268a7 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class BookSeriesDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs index ead34981..9cec0164 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class IsbnDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDtoFixture.cs index 8fa3f11c..da5df880 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDtoFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class UpdateBookCoverDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs index 6695be24..77682008 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class WrittenContentMetadataDtoFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs index 99d99d04..75b9b7d3 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Models; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class SectionModelFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs index 56abddbb..7db5bd83 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class AddRoleRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs index 73d036cf..c3312919 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class DeleteRoleRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs index 8c6d4dda..6a72e48a 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class UpdateRoleRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs index b3f910af..8b362a7f 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class UpdateUserRoleAndPermissionsRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs index daf3c6d6..9a174f29 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Directories; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class GetDirectoriesRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs index 4a409d37..a56ad130 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Path; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ValidatePathRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestFixture.cs index 626bb5ac..d01d9332 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Thumbnails; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class GetThumbnailRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs index 01dfbaaa..acf16aed 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class GetBooksLiteRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs index e2997aa2..1bb0ade3 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class DeleteLibraryRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequestFixture.cs new file mode 100644 index 00000000..80ef2935 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequestFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available path parts are retrieved. + /// The created . + public GetLibraryPathTemplatePartsRequest Create( + string? libraryType = null) + { + return new GetLibraryPathTemplatePartsRequest(libraryType ?? "Music"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs index 57f2062f..90552352 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class GetBookRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs index 85ef74c6..f992877d 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class GetBooksViewRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs index 7e0dac00..8d29f1f5 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs @@ -15,7 +15,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class UpdateBookRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs index 9a6eef5d..ed6112c1 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ReorderLibraryArtworkProvidersRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs index 18439e07..ff5d3855 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class ReorderLibraryMetadataProvidersRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs index 8ee3fc34..5faccb34 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class SetLibraryArtworkProviderEnabledRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs index 4ee3fa19..c2ff8329 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class SetLibraryMetadataProviderEnabledRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs index 973f54ea..90f776b4 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; /// -/// Fixture class for generating test data. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] public class UpdatePluginSettingsRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/AddScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/AddScheduledJobRequestFixture.cs index 19c3d29c..9dbac79a 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/AddScheduledJobRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/AddScheduledJobRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class AddScheduledJobRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/FireScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/FireScheduledJobRequestFixture.cs index 04c48d00..df3bae45 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/FireScheduledJobRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/FireScheduledJobRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class FireScheduledJobRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/GetScheduledJobHistoryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/GetScheduledJobHistoryRequestFixture.cs index aa730ea8..783c6a73 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/GetScheduledJobHistoryRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/GetScheduledJobHistoryRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class GetScheduledJobHistoryRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/RemoveScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/RemoveScheduledJobRequestFixture.cs index 08ce2872..7ca186ef 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/RemoveScheduledJobRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/RemoveScheduledJobRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class RemoveScheduledJobRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StartScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StartScheduledJobRequestFixture.cs index 486a4903..4dc41d72 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StartScheduledJobRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StartScheduledJobRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class StartScheduledJobRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StopScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StopScheduledJobRequestFixture.cs index d61b4452..93be7d4c 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StopScheduledJobRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StopScheduledJobRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class StopScheduledJobRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequestFixture.cs index 1d162c96..88fd5ff2 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequestFixture.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class UpdateSchedulerDisplayPreferencesRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs index fdd4991b..86efae8c 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class DeleteThemeRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs index 2790427b..2ebc76ed 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class GetThemeArchiveRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs index a0e2c25c..95ce39b3 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class GetThemeAssetRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs index d90e2661..8538a9d4 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class RestoreThemeRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs index 9da2f514..9fa87d51 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class SetCurrentThemeRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs index 2c3cd82d..8c6e9c14 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Tools; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class SetLanguageRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs index a9c5a850..49a9d96f 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement.Authentication; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class LoginViewRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs index ada59d24..a43ef34e 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ChangePasswordRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs index ff93376b..cf440a9e 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class LoginRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs index 5ece6620..ad4e3130 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class RecoverPasswordRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs index eecebc32..252fcdf0 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class RegisterRequestFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs index e6f47bde..a8d19d08 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs @@ -11,7 +11,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class GetAuthorizationResponseFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs index da00e31c..146f372d 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs @@ -9,7 +9,7 @@ using System.Linq; namespace Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; /// -/// Fixture class for generating test data. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class RegisterResponseFixture diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs index edf90f82..fc68fe00 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web; -using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; using Microsoft.AspNetCore.Mvc.Testing; using System; using System.Diagnostics.CodeAnalysis; @@ -28,6 +28,8 @@ public record AuthenticatedWebClient(HttpClient Client, string AntiforgeryToken) [ExcludeFromCodeCoverage] public static partial class WebTestHelpers { + private static readonly LoginRequestFixture s_loginRequestFixture = new(); + private const string LOGIN_PAGE_PATH = "/en-us/auth/login"; private const string LOGIN_ENDPOINT_PATH = "/en-us/auth/api-login"; // the change password page renders an antiforgery token for the authenticated user without calling the remote API @@ -81,7 +83,7 @@ public static partial class WebTestHelpers { HttpRequestMessage loginRequest = new(HttpMethod.Post, LOGIN_ENDPOINT_PATH) { - Content = JsonContent.Create(new LoginRequest(Username: username, Password: password)) + Content = JsonContent.Create(s_loginRequestFixture.Create(username: username, password: password)) }; // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Validation/ValidationOptionsFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Validation/ValidationOptionsFixture.cs new file mode 100644 index 00000000..6855b627 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Validation/ValidationOptionsFixture.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Validation; + +/// +/// Test-support placeholder options type used as the validated options in validation options tests. +/// +[ExcludeFromCodeCoverage] +public class ValidationOptionsFixture +{ + /// + /// Creates a new instance. + /// + /// A configured instance. + public ValidationOptionsFixture Create() + { + return new ValidationOptionsFixture(); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj b/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj index 5a1ef4ce..3fa4238f 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\web\ - false false false diff --git a/tests/Common/Lumina.TestPlugin/Lumina.TestPlugin.csproj b/tests/Common/Lumina.TestPlugin/Lumina.TestPlugin.csproj index 788aea94..8a7bbc17 100644 --- a/tests/Common/Lumina.TestPlugin/Lumina.TestPlugin.csproj +++ b/tests/Common/Lumina.TestPlugin/Lumina.TestPlugin.csproj @@ -5,7 +5,6 @@ disable enable $(SolutionDir)..\bin\api\ - false false false diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs index 38a71a90..cc42b970 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs @@ -30,6 +30,7 @@ public class LibraryRepositoryTests { private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LibraryContentLocationEntityFixture _libraryContentLocationEntityFixture = new(); [Fact] public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeTheLibraryAudit() @@ -78,7 +79,7 @@ public class LibraryRepositoryTests LibraryEntity incoming = await LoadDetachedLibraryAsync(context, library.Id); incoming.ContentLocations.Clear(); foreach (string path in new[] { "/media/one", "/media/keep", "/media/three" }) - incoming.ContentLocations.Add(new LibraryContentLocationEntity { Path = path }); + incoming.ContentLocations.Add(_libraryContentLocationEntityFixture.Create(path: path)); // Act Result result = await sut.UpdateAsync(incoming, CancellationToken.None); diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs index 8769e260..949f166d 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs @@ -73,4 +73,42 @@ public class LibraryScanRepositoryTests Assert.Null(reloadedScan.UpdatedOnUtc); Assert.Null(reloadedScan.UpdatedBy); } + + [Fact] + public async Task FailInterruptedScansAsync_WhenScansArePendingOrRunning_ShouldMarkThemAsFailedAndLeaveTheOthersUnchanged() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryscanrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + LibraryScanRepository sut = new(context); + + UserEntity storedUser = _userEntityFixture.Create(username: "scan-user", password: "Password123"); + context.Users.Add(storedUser); + LibraryEntity storedLibrary = _libraryEntityFixture.Create(userId: storedUser.Id); + context.Libraries.Add(storedLibrary); + await context.SaveChangesAsync(); + + LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Pending, libraryEntity: storedLibrary); + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Running, libraryEntity: storedLibrary); + LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Completed, libraryEntity: storedLibrary); + LibraryScanEntity canceledScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Canceled, libraryEntity: storedLibrary); + LibraryScanEntity failedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Failed, libraryEntity: storedLibrary); + context.LibraryScans.AddRange(pendingScan, runningScan, completedScan, canceledScan, failedScan); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.FailInterruptedScansAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + context.ChangeTracker.Clear(); + Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == pendingScan.Id)).Status); + Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == runningScan.Id)).Status); + Assert.Equal(LibraryScanJobStatus.Completed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == completedScan.Id)).Status); + Assert.Equal(LibraryScanJobStatus.Canceled, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == canceledScan.Id)).Status); + Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == failedScan.Id)).Status); + } } diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs new file mode 100644 index 00000000..9571ecae --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.DataAccess.Core.Repositories.MediaContributors; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MediaContributors; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorRepositoryTests +{ + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + + [Fact] + public async Task InsertAsync_WhenContributorWithSameDisplayNameInDifferentCaseExists_ShouldReturnError() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + MediaContributorRepository sut = new(context); + + MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King"); + context.MediaContributors.Add(existingContributor); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + + // Act + // The comparison is case-insensitive, matching the unique index on the display name. + Result result = await sut.InsertAsync(_mediaContributorEntityFixture.Create(displayName: "stephen king"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorAlreadyExists, result.FirstError); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs index b46416e8..7a2e5df1 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.UoW; @@ -47,7 +48,7 @@ public class LuminaDbContextTests : IDisposable // Assert // The count assertion fails when a table is added or removed, reminding to update the assertions below. - Assert.Equal(46, tableNames.Length); + Assert.Equal(62, tableNames.Length); Assert.Contains("Books", tableNames); Assert.Contains("Users", tableNames); Assert.Contains("UserSettings", tableNames); @@ -69,6 +70,7 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("Tags", tableNames); Assert.Contains("Genres", tableNames); Assert.Contains("LibraryContentLocations", tableNames); + Assert.Contains("LibraryPathTemplateParts", tableNames); Assert.Contains("BookTags", tableNames); Assert.Contains("BookGenres", tableNames); Assert.Contains("BookRatings", tableNames); @@ -81,19 +83,31 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("ScheduledJobExecutions", tableNames); Assert.Contains("SchedulerDisplayPreferences", tableNames); Assert.Contains("Artists", tableNames); + Assert.Contains("ArtistAliases", tableNames); + Assert.Contains("ArtistIpis", tableNames); + Assert.Contains("ArtistIsnis", tableNames); + Assert.Contains("ArtistTags", tableNames); + Assert.Contains("ArtistGenres", tableNames); + Assert.Contains("ArtistRatings", tableNames); Assert.Contains("Albums", tableNames); - Assert.Contains("Tracks", tableNames); - Assert.Contains("ArtistContributors", tableNames); - Assert.Contains("AlbumContributors", tableNames); + Assert.Contains("AlbumReleaseTypes", tableNames); + Assert.Contains("AlbumCatalogNumbers", tableNames); Assert.Contains("AlbumGenres", tableNames); Assert.Contains("AlbumRatings", tableNames); Assert.Contains("AlbumTags", tableNames); + Assert.Contains("Tracks", tableNames); Assert.Contains("TrackContributors", tableNames); Assert.Contains("TrackGenres", tableNames); Assert.Contains("TrackIsrcs", tableNames); Assert.Contains("TrackMoods", tableNames); Assert.Contains("TrackRatings", tableNames); Assert.Contains("TrackTags", tableNames); + Assert.Contains("TrackWorkLanguages", tableNames); + Assert.Contains("TrackWorkIswcs", tableNames); + Assert.Contains("ArtistContributors", tableNames); + Assert.Contains("AlbumContributors", tableNames); + Assert.Contains("MusicArtwork", tableNames); + Assert.Contains("MusicLibraryScanItemMetadata", tableNames); } [Fact] diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj index 25d7a895..fdd0531c 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Lumina.DataAccess.IntegrationTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs new file mode 100644 index 00000000..50f9f53d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs @@ -0,0 +1,763 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Infrastructure.Fixtures.Common.Setup; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkServiceTests +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly IHttpClientFactory _mockHttpClientFactory; + private readonly IOptions _mockMediaSettingsOptions; + private readonly MusicArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + private readonly StubHttpMessageHandler _stubHttpMessageHandler = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + + _mockHttpClientFactory = Substitute.For(); + _mockHttpClientFactory.CreateClient(Arg.Any()).Returns(new HttpClient(_stubHttpMessageHandler)); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music"); + _mockMediaSettingsOptions = Substitute.For>(); + _mockMediaSettingsOptions.Value.Returns(mediaSettings); + + _sut = new MusicArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg"); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpg"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Theory] + [InlineData(ArtworkType.Cover, 0, "cover.jpg")] // the front cover uses the bare type name + [InlineData(ArtworkType.Back, 0, "back.jpg")] // the back cover uses the bare type name + [InlineData(ArtworkType.Medium, 0, "medium.jpg")] // a single medium uses the bare type name + [InlineData(ArtworkType.Booklet, 0, "booklet.jpg")] // the first booklet page uses the bare type name + [InlineData(ArtworkType.Booklet, 2, "booklet-2.jpg")] // a further booklet page is suffixed with its ordinal + [InlineData(ArtworkType.Liner, 1, "liner-1.jpg")] // a liner note page is suffixed with its ordinal + [InlineData(ArtworkType.Other, 0, "other.jpg")] // any other type falls back to the generic name + public async Task SaveAlbumArtworkAsync_WhenTheArtworkHasAType_ShouldNameTheFileAfterTheTypeAndOrdinal(ArtworkType artworkType, int ordinal, string expectedFileName) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "artwork.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), expectedFileName) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, expectedFileName)))); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), expectedFileName); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenArtistNameIsMissing_ShouldUseUnknownForTheDirectorySegment() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName: "Unknown", albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockPathService.Received(1).SanitizeSegment("Unknown"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath() + { + // Arrange + string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}"); + Directory.CreateDirectory(targetDirectory); + string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}"); + if (!TryCreateJunction(linkPath, targetDirectory)) + { + Directory.Delete(targetDirectory, true); + return; // The environment does not support creating reparse points. + } + + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + if (OperatingSystem.IsWindows()) + Directory.Delete(linkPath, true); + else + File.Delete(linkPath); + Directory.Delete(targetDirectory, true); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage() + { + // Arrange + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.None)); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[1024]); + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path.StartsWith(Path.GetTempPath())), + Arg.Any(), + true); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(sourcePath)); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path == sourcePath), + Arg.Any(), + true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + MockPathBuilding(); + + // Act + async Task Act() + { + await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenImageTypeDetectionFails_ShouldReturnTheError() + { + // Arrange + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type")); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenCreatingTheArtworkDirectoryFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Directory.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenDirectoryExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Directory.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenCopyingTheArtworkFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().RenameFile(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRenamingTheCopiedArtworkFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenArtistNameCannotBeSanitized_ShouldReturnInvalidPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media"); + string musicPath = Path.Combine(mediaRoot, "music"); + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot)); + _mockPathService.CombinePath(mediaRoot, "music").Returns(Result.From(musicPath)); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return name == $"{libraryName}-{libraryId}" + ? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)) + : Errors.FileSystemManagement.InvalidPath; + }); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public void DeleteAlbumArtwork_WhenCalled_ShouldDeleteEveryFileInTheAlbumDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); + FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg")); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([coverFileId, bookletFileId])); + _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); + + // Act + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).DeleteFile(coverFileId); + _mockFileProviderService.Received(1).DeleteFile(bookletFileId); + } + + /// + /// Stubs the path service so that building the artwork directory paths succeeds. + /// + private void MockPathBuilding() + { + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); + }); + + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + } + + /// + /// Stubs the path and file system services so that the artwork is stored into the given directory. + /// + /// The file system path of the directory into which the artwork is stored. + private void MockArtworkDirectoryStubs(string artworkDirectoryPath) + { + MockPathBuilding(); + + // Every directory except the artwork directory itself already exists, so that only the final directory is created. + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(callInfo => Result.From(!string.Equals(callInfo.Arg().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase))); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())))); + + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + } + + /// + /// Builds the file system path of the directory that the artwork of the album is stored into. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The expected file system path of the album artwork directory. + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "music", + $"{libraryName}-{libraryId}", + artistName, + $"{albumTitle}-{albumId}"); + } + + /// + /// Creates a temporary image file and returns its path. + /// + /// The size of the temporary image file, in bytes. + /// The file system path of the created temporary image file. + private static string CreateTempImageFile(int smallImageBytes = 1024) + { + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[smallImageBytes]); + return sourcePath; + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + Process process = Process.Start(startInfo)!; + process.WaitForExit(5000); + return process.ExitCode == 0; + } + catch (Exception) + { + return false; + } + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 13b9f52b..5456488f 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -65,7 +65,7 @@ public class BookArtworkServiceTests _mockPathService.PathSeparator.Returns('\\'); _mockHttpClientFactory = Substitute.For(); - _mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler)); + _mockHttpClientFactory.CreateClient(Arg.Any()).Returns(new HttpClient(_stubHttpMessageHandler)); MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books"); _mockMediaSettingsOptions = Substitute.For>(); @@ -98,9 +98,9 @@ public class BookArtworkServiceTests _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(copiedFileId)); - string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg"); + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg"); FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Result.From(renamedFileId)); // Act @@ -113,7 +113,7 @@ public class BookArtworkServiceTests Arg.Is(pathId => pathId.Path == sourcePath), Arg.Any(), true); - _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpeg"); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpg"); } finally { @@ -140,10 +140,10 @@ public class BookArtworkServiceTests string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Result.From(renamedFileId)); // Act @@ -264,8 +264,8 @@ public class BookArtworkServiceTests _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Result.From(renamedFileId)); // Act @@ -327,10 +327,10 @@ public class BookArtworkServiceTests string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Result.From(renamedFileId)); // Act @@ -521,7 +521,7 @@ public class BookArtworkServiceTests MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork")); // Act diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs index 043d7e42..2fe9cfdb 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs @@ -50,7 +50,7 @@ public class BookReadingServiceTests : IDisposable private readonly ReadingDocumentDtoFixture _readingDocumentDtoFixture = new(); private readonly ReadingSpineItemDtoFixture _readingSpineItemDtoFixture = new(); private readonly ReadingResourceInfoDtoFixture _readingResourceInfoDtoFixture = new(); - private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -70,7 +70,7 @@ public class BookReadingServiceTests : IDisposable _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository); - LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true); + LibraryBookReaderConfigurationEntity enabledConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true); _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any()) .Returns(Result.From(enabledConfiguration)); diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Lumina.Infrastructure.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Lumina.Infrastructure.IntegrationTests.csproj index f442a0d8..23a28c44 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Lumina.Infrastructure.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Lumina.Infrastructure.IntegrationTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs index e337b06b..d4e78cbe 100644 --- a/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs +++ b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs @@ -4,6 +4,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Plugins.Calibre.Core; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; @@ -34,12 +35,12 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.NotNull(result); - Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); - Assert.Null(result.RemoteUrl); + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), artwork.LocalPath); + Assert.Null(artwork.RemoteUrl); } finally { @@ -59,10 +60,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { @@ -85,10 +86,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { @@ -108,10 +109,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { @@ -130,10 +131,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { @@ -153,10 +154,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { diff --git a/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests.csproj index 4309ec26..a5cba043 100644 --- a/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests.csproj @@ -1,10 +1,9 @@ - + net10.0 disable enable - false true diff --git a/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Lumina.Plugins.Epub.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Lumina.Plugins.Epub.IntegrationTests.csproj index 0abab51d..67bc13a0 100644 --- a/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Lumina.Plugins.Epub.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.Plugins.Epub.IntegrationTests/Lumina.Plugins.Epub.IntegrationTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3AlbumMetadataProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3AlbumMetadataProviderTests.cs new file mode 100644 index 00000000..ddbd06ea --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3AlbumMetadataProviderTests.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Lumina.Plugins.ID3.Fixtures.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real tagged audio containers. +/// +[ExcludeFromCodeCoverage] +public class Id3AlbumMetadataProviderTests : IDisposable +{ + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly Id3AlbumMetadataProvider _sut = new(new Id3TagReader()); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3AlbumMetadataProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-album-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryAnAlbum_ShouldReturnTheMappedAlbum() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Album = "The Album"; + file.Tag.AlbumArtists = ["The Album Artist"]; + file.Tag.TrackCount = 10; + file.Tag.DiscCount = 2; + }); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + AlbumMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Album", result.Title); + Assert.Equal(10, result.TotalTracks); + Assert.Equal(2, result.TotalDiscs); + Assert.NotNull(result.Contributors); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Album Artist"); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryNoAlbum_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "untagged.wav"); + TestAudioFileFactory.CreateWav(path); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + AlbumMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheTagsCarryAnAlbum_ShouldReturnASingleCandidate() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Album = "The Album"); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + AlbumMetadataDto candidate = Assert.Single(result); + Assert.Equal("The Album", candidate.Title); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3ArtistMetadataProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3ArtistMetadataProviderTests.cs new file mode 100644 index 00000000..dff187ec --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3ArtistMetadataProviderTests.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Lumina.Plugins.ID3.Fixtures.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real tagged audio containers. +/// +[ExcludeFromCodeCoverage] +public class Id3ArtistMetadataProviderTests : IDisposable +{ + private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new(); + private readonly Id3ArtistMetadataProvider _sut = new(new Id3TagReader()); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3ArtistMetadataProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-artist-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryAnArtist_ShouldReturnTheMappedArtist() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + Guid artistId = Guid.NewGuid(); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Performers = ["The Artist"]; + file.Tag.PerformersSort = ["Artist, The"]; + file.Tag.MusicBrainzArtistId = artistId.ToString(); + }); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + ArtistMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Artist", result.Name); + Assert.Equal("Artist, The", result.SortName); + Assert.Equal(artistId, result.MusicBrainzArtistId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryNoArtist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "untagged.wav"); + TestAudioFileFactory.CreateWav(path); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + ArtistMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheTagsCarryAnArtist_ShouldReturnASingleCandidate() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Performers = ["The Artist"]); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + ArtistMetadataDto candidate = Assert.Single(result); + Assert.Equal("The Artist", candidate.Name); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs new file mode 100644 index 00000000..e2b37e9b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Lumina.Plugins.ID3.Fixtures.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real tagged audio containers. +/// +[ExcludeFromCodeCoverage] +public class Id3TrackMetadataProviderTests : IDisposable +{ + private readonly TrackMetadataLookupDtoFixture _trackMetadataLookupDtoFixture = new(); + private readonly Id3TrackMetadataProvider _sut = new(new Id3TagReader()); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3TrackMetadataProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-track-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryATitle_ShouldReturnTheMappedTrack() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Title = "The Track"; + file.Tag.InitialKey = "C#m"; + file.Tag.BeatsPerMinute = 128; + file.Tag.Performers = ["The Artist"]; + }); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + AudioMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Track", result.Title); + Assert.Equal(MusicKey.CSharpMinor, result.Key); + Assert.Equal(128, result.Bpm); + Assert.NotNull(result.Contributors); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Artist"); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryNoTitle_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "untagged.wav"); + TestAudioFileFactory.CreateWav(path); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + AudioMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheTagsCarryATitle_ShouldReturnASingleCandidate() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Title = "The Track"); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + AudioMetadataDto candidate = Assert.Single(result); + Assert.Equal("The Track", candidate.Title); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs new file mode 100644 index 00000000..60a4a815 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs @@ -0,0 +1,480 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Tags; +using Lumina.Plugins.ID3.Fixtures.Core.Tags; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.ID3.IntegrationTests.Core.Tags; + +/// +/// Contains integration tests for the class, reading real audio containers through the tagging library. +/// +[ExcludeFromCodeCoverage] +public class Id3TagReaderTests : IDisposable +{ + private readonly Id3TagReader _sut = new(); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3TagReaderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-reader-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Read_WhenEveryTagIsPresent_ShouldMapEveryProperty() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "all-fields.wav"); + Guid artistId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + Guid releaseGroupId = Guid.NewGuid(); + Guid releaseId = Guid.NewGuid(); + Guid recordingId = Guid.NewGuid(); + Guid releaseTrackId = Guid.NewGuid(); + Guid workId = Guid.NewGuid(); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Title = "The Track"; + file.Tag.Album = "The Album"; + file.Tag.Performers = ["Track Artist"]; + file.Tag.AlbumArtists = ["Album Artist"]; + file.Tag.PerformersSort = ["Track Artist, The"]; + file.Tag.AlbumArtistsSort = ["Album Artist, The"]; + file.Tag.Track = 3; + file.Tag.TrackCount = 12; + file.Tag.Disc = 1; + file.Tag.DiscCount = 2; + file.Tag.Genres = ["Rock/Pop", "Jazz"]; + file.Tag.Composers = ["Composer One/Composer Two"]; + file.Tag.Conductor = "The Conductor"; + file.Tag.RemixedBy = "The Remixer"; + file.Tag.Publisher = "The Label"; + file.Tag.ISRC = "GBAAA0000001"; + file.Tag.InitialKey = "C#m"; + file.Tag.BeatsPerMinute = 128; + file.Tag.AmazonId = "B000000001"; + file.Tag.MusicBrainzArtistId = artistId.ToString(); + file.Tag.MusicBrainzReleaseArtistId = releaseArtistId.ToString(); + file.Tag.MusicBrainzReleaseGroupId = releaseGroupId.ToString(); + file.Tag.MusicBrainzReleaseId = releaseId.ToString(); + file.Tag.MusicBrainzTrackId = recordingId.ToString(); + file.Tag.MusicBrainzReleaseType = "album"; + file.Tag.MusicBrainzReleaseStatus = "official"; + file.Tag.MusicBrainzReleaseCountry = "US"; + TestAudioFileFactory.AddTextFrame(file, "TDRC", "2011-03-14"); + TestAudioFileFactory.AddTextFrame(file, "TDOR", "1975-11-21"); + TestAudioFileFactory.AddUserTextFrame(file, "LYRICIST", "Lyricist One;Lyricist Two"); + TestAudioFileFactory.AddTextFrame(file, "IPLS", "producer", "Producer Person", "engineer", "Engineer Person"); + TestAudioFileFactory.AddUserTextFrame(file, "LANGUAGE", "eng"); + TestAudioFileFactory.AddUserTextFrame(file, "SCRIPT", "Latn"); + TestAudioFileFactory.AddUserTextFrame(file, "CATALOGNUMBER", "CAT-1;CAT-2"); + TestAudioFileFactory.AddUserTextFrame(file, "BARCODE", "1234567890123"); + TestAudioFileFactory.AddUserTextFrame(file, "MEDIA", "CD"); + TestAudioFileFactory.AddUserTextFrame(file, "PACKAGING", "Jewel Case"); + TestAudioFileFactory.AddUserTextFrame(file, "MOODS", "calm;happy"); + TestAudioFileFactory.AddUserTextFrame(file, "WORK", "The Work"); + TestAudioFileFactory.AddUserTextFrame(file, "MUSICBRAINZ_WORKID", workId.ToString()); + TestAudioFileFactory.AddUserTextFrame(file, "MUSICBRAINZ_RELEASETRACKID", releaseTrackId.ToString()); + TestAudioFileFactory.AddUserTextFrame(file, "website", "https://artist.example"); + }, durationMs: 2000); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Track", result.Title); + Assert.Equal("The Album", result.Album); + Assert.Equal(["Track Artist"], result.TrackArtists); + Assert.Equal(["Album Artist"], result.AlbumArtists); + Assert.Equal("Album Artist, The", result.AlbumArtistSortName); + Assert.Equal("Track Artist, The", result.TrackArtistSortName); + Assert.Equal(3u, result.TrackNumber); + Assert.Equal(12u, result.TrackCount); + Assert.Equal(1u, result.DiscNumber); + Assert.Equal(2u, result.DiscCount); + Assert.Equal(2011, result.Year); + Assert.Equal(new DateOnly(1975, 11, 21), result.OriginalReleaseDate); + Assert.Equal(1975, result.OriginalReleaseYear); + Assert.Equal(["Rock", "Pop", "Jazz"], result.Genres); + Assert.Equal(["Composer One", "Composer Two"], result.Composers); + Assert.Equal(["Lyricist One", "Lyricist Two"], result.Lyricists); + Assert.Equal(["The Conductor"], result.Conductors); + Assert.Equal(["The Remixer"], result.Remixers); + Assert.Equal([("producer", "Producer Person"), ("engineer", "Engineer Person")], result.InvolvedPeople); + Assert.Equal("eng", result.Language); + Assert.Equal("Latn", result.Script); + Assert.Equal("The Label", result.Label); + Assert.Equal(["CAT-1", "CAT-2"], result.CatalogNumbers); + Assert.Equal("1234567890123", result.Barcode); + Assert.Equal(["album"], result.ReleaseTypes); + Assert.Equal("official", result.ReleaseStatus); + Assert.Equal("US", result.ReleaseCountry); + Assert.Equal("CD", result.MediaFormat); + Assert.Equal("Jewel Case", result.Packaging); + Assert.Equal("B000000001", result.Asin); + Assert.Equal(["GBAAA0000001"], result.Isrcs); + Assert.Equal(["calm", "happy"], result.Moods); + Assert.Equal("The Work", result.WorkTitle); + Assert.Equal("C#m", result.MusicKey); + Assert.Equal(128, result.Bpm); + Assert.Equal(2, result.DurationInSeconds); + Assert.Equal(44100, result.SampleRate); + Assert.Equal(1, result.Channels); + Assert.Equal(16, result.BitDepth); + Assert.True(result.Bitrate > 0); + Assert.Equal("PCM Audio", result.AudioCodec); + Assert.Equal("https://artist.example", result.Website); + Assert.Equal(artistId.ToString(), result.MusicBrainzArtistId); + Assert.Equal(releaseArtistId.ToString(), result.MusicBrainzReleaseArtistId); + Assert.Equal(releaseGroupId.ToString(), result.MusicBrainzReleaseGroupId); + Assert.Equal(releaseId.ToString(), result.MusicBrainzReleaseId); + Assert.Equal(recordingId.ToString(), result.MusicBrainzRecordingId); + Assert.Equal(releaseTrackId.ToString(), result.MusicBrainzReleaseTrackId); + Assert.Equal(workId.ToString(), result.MusicBrainzWorkId); + } + + [Fact] + public void Read_WhenTheFileIsUntagged_ShouldReturnASnapshotWithTheAudioProperties() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "untagged.wav"); + TestAudioFileFactory.CreateWav(path); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Title); + Assert.Null(result.Album); + Assert.Empty(result.TrackArtists); + Assert.Empty(result.AlbumArtists); + Assert.Null(result.AlbumArtistSortName); + Assert.Null(result.TrackArtistSortName); + Assert.Equal(0u, result.TrackNumber); + Assert.Equal(0u, result.TrackCount); + Assert.Equal(0u, result.DiscNumber); + Assert.Equal(0u, result.DiscCount); + Assert.Null(result.Year); + Assert.Null(result.OriginalReleaseDate); + Assert.Null(result.OriginalReleaseYear); + Assert.Empty(result.Genres); + Assert.Empty(result.Composers); + Assert.Empty(result.Lyricists); + Assert.Empty(result.Conductors); + Assert.Empty(result.Remixers); + Assert.Empty(result.InvolvedPeople); + Assert.Null(result.Language); + Assert.Null(result.Script); + Assert.Null(result.Label); + Assert.Empty(result.CatalogNumbers); + Assert.Null(result.Barcode); + Assert.Empty(result.ReleaseTypes); + Assert.Null(result.ReleaseStatus); + Assert.Null(result.ReleaseCountry); + Assert.Null(result.MediaFormat); + Assert.Null(result.Packaging); + Assert.Null(result.Asin); + Assert.Empty(result.Isrcs); + Assert.Empty(result.Moods); + Assert.Null(result.WorkTitle); + Assert.Null(result.MusicKey); + Assert.Null(result.Bpm); + Assert.Equal(44100, result.SampleRate); + Assert.Equal(1, result.Channels); + Assert.Equal(16, result.BitDepth); + Assert.Equal("PCM Audio", result.AudioCodec); + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Null(result.MusicBrainzReleaseTrackId); + Assert.Null(result.MusicBrainzWorkId); + } + + [Fact] + public void Read_WhenTheFileIsNotAnAudioContainer_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "not-audio.txt"); + File.WriteAllText(path, "this is not an audio file"); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Read_WhenCalledTwiceForTheSamePath_ShouldReturnTheCachedSnapshot() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "cached.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Title = "The Track"); + + // Act + Id3TagDto? first = _sut.Read(path); + Id3TagDto? second = _sut.Read(path); + + // Assert + Assert.NotNull(first); + Assert.Same(first, second); + } + + [Theory] + [InlineData("2011-03-14", 2011)] // a full date yields its year + [InlineData("2011", 2011)] // a bare year is matched by the year pattern + [InlineData("released in 1999 remastered", 1999)] // a year embedded in free form text is still matched + public void Read_WhenTheReleaseDateIsPresent_ShouldParseTheYear(string releaseDate, int expectedYear) + { + // Arrange + string path = Path.Combine(_temporaryDirectory, $"release-date-{Guid.NewGuid():N}.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUserTextFrame(file, "TDRC", releaseDate)); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(expectedYear, result.Year); + } + + [Fact] + public void Read_WhenOnlyTheYearTagIsPresent_ShouldMapTheYear() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "year-only.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Year = 1999); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(1999, result.Year); + Assert.Null(result.OriginalReleaseDate); + Assert.Equal(1999, result.OriginalReleaseYear); + } + + [Fact] + public void Read_WhenOnlyTheOriginalYearIsPresent_ShouldUseItForTheOriginalReleaseYear() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "original-year.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Year = 2000; + TestAudioFileFactory.AddUserTextFrame(file, "originalyear", "1960"); + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(2000, result.Year); + Assert.Null(result.OriginalReleaseDate); + Assert.Equal(1960, result.OriginalReleaseYear); + } + + [Fact] + public void Read_WhenOnlyTheOriginalReleaseDateIsPresent_ShouldDeriveTheOriginalReleaseYearFromIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "original-date.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + TestAudioFileFactory.AddUserTextFrame(file, "TDRC", "2011-03-14"); + TestAudioFileFactory.AddUserTextFrame(file, "TDOR", "1975-11-21"); + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(new DateOnly(1975, 11, 21), result.OriginalReleaseDate); + Assert.Equal(1975, result.OriginalReleaseYear); + } + + [Fact] + public void Read_WhenTheLabelIsOnlyCarriedByTheExtendedTag_ShouldUseIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "extended-label.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUserTextFrame(file, "LABEL", "The Extended Label")); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Extended Label", result.Label); + } + + [Fact] + public void Read_WhenTheAsinIsOnlyCarriedByTheExtendedTag_ShouldUseIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "extended-asin.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUserTextFrame(file, "ASIN", "B000000001")); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("B000000001", result.Asin); + } + + [Fact] + public void Read_WhenTheLanguageUsesTheAlternativeKey_ShouldStillMapIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tlan.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUserTextFrame(file, "TLAN", "deu")); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("deu", result.Language); + } + + [Fact] + public void Read_WhenTheIsrcIsBothInTheDedicatedAndTheExtendedTag_ShouldKeepOnlyDistinctValues() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "isrc-merge.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.ISRC = "GBAAA0000001"; + TestAudioFileFactory.AddTextFrame(file, "TSRC", "GBAAA0000001", "USRC17607839"); + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(["GBAAA0000001", "USRC17607839"], result.Isrcs); + } + + [Fact] + public void Read_WhenSeveralReleaseTypesArePacked_ShouldSplitThemOnSemicolons() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "release-types.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.MusicBrainzReleaseType = "album;live"); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(["album", "live"], result.ReleaseTypes); + } + + [Fact] + public void Read_WhenTheWebsiteIsAUrlLinkFrame_ShouldMapIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "woar.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUrlFrame(file, "WOAR", "https://artist.example")); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("https://artist.example", result.Website); + } + + [Fact] + public void Read_WhenAFrameCarriesNoDescription_ShouldIgnoreIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "no-description.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + TestAudioFileFactory.AddUserTextFrame(file, "", "orphan"); + file.Tag.Title = "The Track"; + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Track", result.Title); + } + + [Fact] + public void Read_WhenAppleStyleInvolvedPeopleKeysArePresent_ShouldMapThem() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "apple-people.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + TestAudioFileFactory.AddUserTextFrame(file, "performer", "Performer Person"); + TestAudioFileFactory.AddUserTextFrame(file, "PRODUCER", "Producer Person"); + TestAudioFileFactory.AddUserTextFrame(file, "ENGINEER", "Engineer Person"); + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal([("performer", "Performer Person"), ("producer", "Producer Person"), ("engineer", "Engineer Person")], result.InvolvedPeople); + } + + [Fact] + public void Read_WhenMoreThanTheCacheLimitFilesAreRead_ShouldEvictTheOldestSnapshot() + { + // Arrange + string[] paths = new string[513]; + for (int index = 0; index < paths.Length; index++) + { + paths[index] = Path.Combine(_temporaryDirectory, $"cache-{index}.wav"); + TestAudioFileFactory.CreateWav(paths[index], durationMs: 1); + } + Id3TagDto? firstBeforeEviction = _sut.Read(paths[0]); + + // Act + for (int index = 1; index < paths.Length; index++) + _sut.Read(paths[index]); + Id3TagDto? firstAfterEviction = _sut.Read(paths[0]); + Id3TagDto? last = _sut.Read(paths[^1]); + + // Assert + Assert.NotNull(firstBeforeEviction); + Assert.NotNull(firstAfterEviction); + // The first snapshot was evicted to make room, so reading it again produced a fresh snapshot. + Assert.NotSame(firstBeforeEviction, firstAfterEviction); + // The most recently read snapshot is still cached. + Assert.Same(_sut.Read(paths[^1]), last); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Lumina.Plugins.ID3.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Lumina.Plugins.ID3.IntegrationTests.csproj new file mode 100644 index 00000000..6c8c9d49 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Lumina.Plugins.ID3.IntegrationTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicAlbumArtworkProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicAlbumArtworkProviderTests.cs new file mode 100644 index 00000000..b30fbf7d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicAlbumArtworkProviderTests.cs @@ -0,0 +1,300 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real image and audio files from the file system. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicAlbumArtworkProviderTests : IDisposable +{ + private static readonly byte[] s_embeddedCoverBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0x01, 0x02, 0x03, 0xFF, 0xD9]; + + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly LocalMusicArtworkSettingsDtoFixture _localMusicArtworkSettingsDtoFixture = new(); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public LocalMusicAlbumArtworkProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-album-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("Local Music Artwork", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Arrange + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasDiskImages_ShouldReturnTheDiskArtwork() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav")); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null), + new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.png"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasACoverOnDisk_ShouldNotExtractTheEmbeddedCover() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "cover.jpg"), artwork.LocalPath); + Assert.Null(artwork.RemoteUrl); + Assert.False(artwork.IsTemporary); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndExtractionIsEnabled_ShouldReturnTheEmbeddedCover() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(ArtworkType.Back, result[0].Type); + Assert.Equal(0, result[0].Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "back.png"), result[0].LocalPath); + Assert.Null(result[0].RemoteUrl); + Assert.False(result[0].IsTemporary); + Assert.Equal(ArtworkType.Cover, result[1].Type); + Assert.Equal(0, result[1].Ordinal); + Assert.NotNull(result[1].LocalPath); + Assert.EndsWith(".jpg", result[1].LocalPath); + Assert.True(File.Exists(result[1].LocalPath)); + Assert.Equal(s_embeddedCoverBytes, File.ReadAllBytes(result[1].LocalPath!)); + Assert.Null(result[1].RemoteUrl); + Assert.True(result[1].IsTemporary); + File.Delete(result[1].LocalPath!); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndExtractionIsDisabled_ShouldReturnOnlyTheDiskArtwork() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: false); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Back, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "back.png"), artwork.LocalPath); + Assert.Null(artwork.RemoteUrl); + Assert.False(artwork.IsTemporary); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndTheTrackHasNoEmbeddedCover_ShouldReturnOnlyTheDiskArtwork() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav")); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Back, artwork.Type); + Assert.Equal(Path.Combine(albumDirectory, "back.png"), artwork.LocalPath); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheTrackHasNoImagesAtAll_ShouldReturnEmpty() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav")); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no artwork + [InlineData("")] // an empty path contributes no artwork + [InlineData(" ")] // a white space path contributes no artwork + [InlineData("track.flac")] // a path without a directory part contributes no artwork + public async Task GetArtworkAsync_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath) + { + // Arrange + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheTrackDirectoryDoesNotExist_ShouldReturnEmpty() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Album", "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav")); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + Task Act() + { + return sut.GetArtworkAsync(lookup, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + /// + /// Creates a whose settings provider carries the provided embedded cover extraction setting. + /// + /// Whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// The created provider. + private LocalMusicAlbumArtworkProvider CreateProvider(bool shouldExtractEmbeddedCover) + { + LocalMusicArtworkSettingsProvider settingsProvider = new( + null, + Guid.NewGuid(), + _localMusicArtworkSettingsDtoFixture.Create(shouldExtractEmbeddedCover: shouldExtractEmbeddedCover)); + return new LocalMusicAlbumArtworkProvider(settingsProvider); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtistArtworkProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtistArtworkProviderTests.cs new file mode 100644 index 00000000..a612ec61 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtistArtworkProviderTests.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real image files from the file system. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtistArtworkProviderTests : IDisposable +{ + private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new(); + private readonly LocalMusicArtistArtworkProvider _sut = new(); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public LocalMusicArtistArtworkProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artist-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Local Music Artwork", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheArtistDirectoryCarriesImages_ShouldReturnTheArtistArtwork() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(artistDirectory, "banner.png")); + TestImageFileFactory.CreateWebp(Path.Combine(artistDirectory, "logo.webp")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(artistDirectory, "folder.jpg"), null), + new(ArtworkType.Banner, 0, Path.Combine(artistDirectory, "banner.png"), null), + new(ArtworkType.Logo, 0, Path.Combine(artistDirectory, "logo.webp"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public async Task GetArtworkAsync_WhenNoArtistImagesExist_ShouldReturnEmpty() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "back.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no artwork + [InlineData("")] // an empty path contributes no artwork + [InlineData(" ")] // a white space path contributes no artwork + [InlineData("track.flac")] // a path without a directory part contributes no artwork + public async Task GetArtworkAsync_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath) + { + // Arrange + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheTrackDirectoryDoesNotExist_ShouldReturnEmpty() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Artist", "track.flac"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldStillReturnTheDiskArtwork() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, cancellationTokenSource.Token); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(Path.Combine(artistDirectory, "folder.jpg"), artwork.LocalPath); + } + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkEmbeddedCoverExtractorTests.cs b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkEmbeddedCoverExtractorTests.cs new file mode 100644 index 00000000..8ce06ac6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkEmbeddedCoverExtractorTests.cs @@ -0,0 +1,198 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real audio containers that carry embedded pictures. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkEmbeddedCoverExtractorTests : IDisposable +{ + private static readonly byte[] s_coverBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0x11, 0x22, 0x33, 0xFF, 0xD9]; + + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public LocalMusicArtworkEmbeddedCoverExtractorTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-embedded-cover-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Extract_WhenTheTrackCarriesAnEmbeddedCover_ShouldReturnATemporaryCoverArtwork() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, s_coverBytes, "image/jpeg"); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.NotNull(result); + Assert.Equal(ArtworkType.Cover, result.Type); + Assert.Equal(0, result.Ordinal); + Assert.NotNull(result.LocalPath); + Assert.StartsWith(Path.GetTempPath(), result.LocalPath); + Assert.EndsWith(".jpg", result.LocalPath); + Assert.True(File.Exists(result.LocalPath)); + Assert.Equal(s_coverBytes, File.ReadAllBytes(result.LocalPath!)); + Assert.Null(result.RemoteUrl); + Assert.True(result.IsTemporary); + File.Delete(result.LocalPath!); + } + + [Fact] + public void Extract_WhenTheTrackHasNoEmbeddedCover_ShouldReturnNull() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWav(trackPath); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no cover + [InlineData("")] // an empty path contributes no cover + [InlineData(" ")] // a white space path contributes no cover + public void Extract_WhenTheTrackPathIsNullOrEmpty_ShouldReturnNull(string? trackPath) + { + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Extract_WhenTheTrackFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "missing.wav"); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Theory] + [InlineData("image/jpeg", ".jpg")] + [InlineData("image/png", ".png")] + [InlineData("image/webp", ".webp")] + [InlineData("image/bmp", ".bmp")] + [InlineData("image/x-ms-bmp", ".bmp")] + [InlineData("image/gif", ".gif")] + [InlineData("image/tiff", ".tiff")] + [InlineData("IMAGE/PNG", ".png")] // the MIME type is matched without regard to casing + [InlineData(" image/png ", ".png")] // the MIME type is trimmed before it is matched + [InlineData("application/octet-stream", ".jpg")] // an unknown MIME type falls back to the JPEG extension + [InlineData("", ".jpg")] // an empty MIME type falls back to the JPEG extension + [InlineData(null, ".jpg")] // a missing MIME type falls back to the JPEG extension + public void Extract_WhenTheMimeTypeIsProvided_ShouldUseTheMatchingFileExtension(string? mimeType, string expectedExtension) + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, s_coverBytes, mimeType); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.LocalPath); + Assert.EndsWith(expectedExtension, result.LocalPath); + Assert.Equal(s_coverBytes, File.ReadAllBytes(result.LocalPath!)); + Assert.True(result.IsTemporary); + File.Delete(result.LocalPath!); + } + + [Fact] + public void Extract_WhenTheEmbeddedCoverIsExactlyTheMaximumSize_ShouldReturnTheCover() + { + // Arrange + byte[] maximumCover = new byte[10 * 1024 * 1024]; + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, maximumCover, "image/jpeg"); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.LocalPath); + Assert.Equal(maximumCover, File.ReadAllBytes(result.LocalPath!)); + Assert.True(result.IsTemporary); + File.Delete(result.LocalPath!); + } + + [Fact] + public void Extract_WhenTheEmbeddedCoverIsLargerThanTheMaximumSize_ShouldReturnNull() + { + // Arrange + byte[] oversizedCover = new byte[10 * 1024 * 1024 + 1]; + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, oversizedCover, "image/jpeg"); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Extract_WhenTheTrackIsNotAnAudioFile_ShouldReturnNull() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.txt"); + TestAudioFileFactory.CreateUnsupportedFile(trackPath); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Extract_WhenTheAudioFileIsCorrupt_ShouldReturnNull() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.mp3"); + TestAudioFileFactory.CreateUnsupportedFile(trackPath); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkScannerTests.cs b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkScannerTests.cs new file mode 100644 index 00000000..e1a3a25e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkScannerTests.cs @@ -0,0 +1,487 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, scanning real image files on the file system. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkScannerTests : IDisposable +{ + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public LocalMusicArtworkScannerTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artwork-scanner-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheAlbumDirectoryCarriesTheStandardImages_ShouldReturnEachArtworkType() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Artist", "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "front.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet1.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "booklet2.png")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "disk.png")); + TestImageFileFactory.CreateGif(Path.Combine(albumDirectory, "tray.gif")); + TestImageFileFactory.CreateTiff(Path.Combine(albumDirectory, "spine.tiff")); + TestImageFileFactory.CreateBmp(Path.Combine(albumDirectory, "obi.bmp")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "sticker.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "poster.png")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "liner.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null), + new(ArtworkType.Front, 0, Path.Combine(albumDirectory, "front.jpg"), null), + new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.png"), null), + new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet1.jpg"), null), + new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet2.png"), null), + new(ArtworkType.Medium, 0, Path.Combine(albumDirectory, "disk.png"), null), + new(ArtworkType.Tray, 0, Path.Combine(albumDirectory, "tray.gif"), null), + new(ArtworkType.Spine, 0, Path.Combine(albumDirectory, "spine.tiff"), null), + new(ArtworkType.Obi, 0, Path.Combine(albumDirectory, "obi.bmp"), null), + new(ArtworkType.Sticker, 0, Path.Combine(albumDirectory, "sticker.jpg"), null), + new(ArtworkType.Poster, 0, Path.Combine(albumDirectory, "poster.png"), null), + new(ArtworkType.Liner, 0, Path.Combine(albumDirectory, "liner.jpg"), null) + ]; + Assert.Equal(12, result.Count); + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheStemCarriesANumber_ShouldUseItAsTheOrdinal() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet1.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet2.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk1.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk2.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Booklet, 0, Path.Combine(albumDirectory, "booklet.jpg"), null), + new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet1.jpg"), null), + new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet2.jpg"), null), + new(ArtworkType.Medium, 1, Path.Combine(albumDirectory, "disk1.jpg"), null), + new(ArtworkType.Medium, 2, Path.Combine(albumDirectory, "disk2.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheStemHasAHyphenOrUnderscoreBeforeTheNumber_ShouldTrimTheSeparator() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet - 1.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet_2.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet - 1.jpg"), null), + new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet_2.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenBothCoverAndFrontExist_ShouldReturnThemAsDistinctArtworks() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "front.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null), + new(ArtworkType.Front, 0, Path.Combine(albumDirectory, "front.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenSeveralNamesMapToTheSameTypeAndOrdinal_ShouldKeepOnlyThePreferredFile() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disc.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + // Both file names describe the medium of the album, and the one that sorts first by name wins, so that a single image is stored per type and ordinal. + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Medium, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "disc.jpg"), artwork.LocalPath); + Assert.Null(artwork.RemoteUrl); + Assert.False(artwork.IsTemporary); + } + + [Fact] + public void ScanAlbumArtwork_WhenAFileIsNotAnImage_ShouldIgnoreIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateTextFile(Path.Combine(albumDirectory, "notes.txt")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(Path.Combine(albumDirectory, "cover.jpg"), artwork.LocalPath); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheImageExtensionIsUppercase_ShouldIgnoreIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.JPG")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.JPEG")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheImageNameHasDifferentCasing_ShouldIgnoreIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "Cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "BACK.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheImageNameIsNotRecognized_ShouldIgnoreIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "random.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "folder.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "backdrop.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheAlbumIsMultiDiscAndTheParentDirectoryCarriesTheArtwork_ShouldFindIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + string discDirectory = Path.Combine(albumDirectory, "CD1"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.jpg")); + Directory.CreateDirectory(discDirectory); + string trackPath = Path.Combine(discDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null), + new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenBothTheDiscAndTheParentDirectoryCarryTheSameArtwork_ShouldPreferTheNearest() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + string discDirectory = Path.Combine(albumDirectory, "CD1"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(discDirectory, "cover.jpg")); + string trackPath = Path.Combine(discDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(discDirectory, "cover.jpg"), artwork.LocalPath); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheDiscAndTheParentDirectoryCarryDifferentArtworks_ShouldReturnBoth() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + string discDirectory = Path.Combine(albumDirectory, "CD1"); + TestImageFileFactory.CreateJpeg(Path.Combine(discDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.jpg")); + string trackPath = Path.Combine(discDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(discDirectory, "cover.jpg"), null), + new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheArtworkIsMoreThanTwoLevelsAboveTheTrack_ShouldNotFindIt() + { + // Arrange + TestImageFileFactory.CreateJpeg(Path.Combine(_temporaryDirectory, "cover.jpg")); + string trackPath = Path.Combine(_temporaryDirectory, "Album", "CD1", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no artwork + [InlineData("")] // an empty path contributes no artwork + [InlineData(" ")] // a white space path contributes no artwork + [InlineData("track.flac")] // a path without a directory part contributes no artwork + public void ScanAlbumArtwork_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath) + { + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheAlbumDirectoryDoesNotExist_ShouldReturnEmpty() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Album", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheArtistDirectoryCarriesTheStandardImages_ShouldReturnEachArtworkType() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "backdrop.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(artistDirectory, "banner.png")); + TestImageFileFactory.CreateWebp(Path.Combine(artistDirectory, "logo.webp")); + TestImageFileFactory.CreateGif(Path.Combine(artistDirectory, "thumb.gif")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(artistDirectory, "folder.jpg"), null), + new(ArtworkType.Backdrop, 0, Path.Combine(artistDirectory, "backdrop.jpg"), null), + new(ArtworkType.Banner, 0, Path.Combine(artistDirectory, "banner.png"), null), + new(ArtworkType.Logo, 0, Path.Combine(artistDirectory, "logo.webp"), null), + new(ArtworkType.Thumb, 0, Path.Combine(artistDirectory, "thumb.gif"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheDirectoryCarriesOnlyAlbumImages_ShouldReturnEmpty() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "back.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "disk.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheArtistImagesAreInAnAncestorDirectory_ShouldFindThem() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "CD1", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(artistDirectory, "folder.jpg"), artwork.LocalPath); + } + + [Fact] + public void ScanArtistArtwork_WhenSeveralAncestorDirectoriesCarryArtistImages_ShouldPreferTheNearest() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + string albumDirectory = Path.Combine(artistDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "backdrop.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "folder.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + // The nearest ancestor that carries an artist image wins, and the album images of that directory are not part of the artist artwork. + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "folder.jpg"), artwork.LocalPath); + } + + [Fact] + public void ScanArtistArtwork_WhenTheArtistImagesAreBeyondTheSearchDepth_ShouldReturnEmpty() + { + // Arrange + TestImageFileFactory.CreateJpeg(Path.Combine(_temporaryDirectory, "folder.jpg")); + string trackPath = Path.Combine(_temporaryDirectory, "A", "B", "C", "D", "E", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheImageNameHasDifferentCasing_ShouldIgnoreIt() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "Folder.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "Backdrop.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no artwork + [InlineData("")] // an empty path contributes no artwork + [InlineData(" ")] // a white space path contributes no artwork + [InlineData("track.flac")] // a path without a directory part contributes no artwork + public void ScanArtistArtwork_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath) + { + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheAncestorDirectoryDoesNotExist_ShouldReturnEmpty() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Artist", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests.csproj new file mode 100644 index 00000000..f234b332 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests.csproj index e5717587..75e6ce76 100644 --- a/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests/Lumina.Plugins.Pdf.IntegrationTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs index 6d6e3966..da59de5a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -32,6 +33,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable PropertyNameCaseInsensitive = true }; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Gets the username of the currently created test user. @@ -74,9 +76,10 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable await dbContext.SaveChangesAsync(); // authenticate user - LoginRequest loginRequest = new( - Username: user.Username, - Password: "TestPass123!" + LoginRequest loginRequest = _loginRequestFixture.Create( + username: user.Username, + password: "TestPass123!", + includeTotpCode: false ); HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest); @@ -133,9 +136,10 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None); // authenticate user - LoginRequest loginRequest = new( - Username: user.Username, - Password: "TestPass123!" + LoginRequest loginRequest = _loginRequestFixture.Create( + username: user.Username, + password: "TestPass123!", + includeTotpCode: false ); HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs index 2febffe9..7cf488f6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.DataAccess.Core.UoW; @@ -33,6 +34,7 @@ public class AddRoleEndpointTests : IClassFixture { private HttpClient _client; private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -65,9 +67,9 @@ public class AddRoleEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)]; - AddRoleRequest request = new( - RoleName: "Editor", - Permissions: permissions.Select(p => p.Id).ToList() + AddRoleRequest request = _addRoleRequestFixture.Create( + roleName: "Editor", + permissions: permissions.Select(p => p.Id).ToList() ); // Act @@ -95,9 +97,9 @@ public class AddRoleEndpointTests : IClassFixture { // Arrange _client = await _apiFactory.CreateAuthenticatedClientAsync(); - AddRoleRequest request = new( - RoleName: "Editor", - Permissions: [Guid.NewGuid()] + AddRoleRequest request = _addRoleRequestFixture.Create( + roleName: "Editor", + permissions: [Guid.NewGuid()] ); // Act @@ -122,9 +124,9 @@ public class AddRoleEndpointTests : IClassFixture public async Task AddRole_WhenRoleAlreadyExists_ShouldReturnConflict() { // Arrange - AddRoleRequest request = new( - RoleName: "Admin", - Permissions: [Guid.NewGuid()] + AddRoleRequest request = _addRoleRequestFixture.Create( + roleName: "Admin", + permissions: [Guid.NewGuid()] ); // Act @@ -150,9 +152,9 @@ public class AddRoleEndpointTests : IClassFixture { // Arrange using CancellationTokenSource cts = new(); - AddRoleRequest request = new( - RoleName: "Editor", - Permissions: [Guid.NewGuid()] + AddRoleRequest request = _addRoleRequestFixture.Create( + roleName: "Editor", + permissions: [Guid.NewGuid()] ); // Act & Assert diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs index 61082ddd..16334bc6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs @@ -43,7 +43,7 @@ public class AddAlbumEndpointTests : IClassFixture(content, _jsonOptions); Assert.NotNull(artistResponse); Assert.Equal(libraryId, artistResponse!.LibraryId); - Assert.Equal("Queen", artistResponse.Name); + Assert.Equal("Queen", artistResponse.Metadata.Name); Assert.NotNull(artistResponse.Albums); AlbumResponse albumResponse = Assert.Single(artistResponse.Albums!); Assert.Equal("A Night at the Opera", albumResponse.Metadata.Title); @@ -105,7 +106,7 @@ public class AddArtistEndpointTests : IClassFixture artist.Name == "Artist A"); - Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Artist B"); + Assert.Contains(paginatedArtists.Data, artist => artist.Metadata.Name == "Artist A"); + Assert.Contains(paginatedArtists.Data, artist => artist.Metadata.Name == "Artist B"); } [Fact] @@ -100,7 +100,7 @@ public class GetArtistsEndpointTests : IClassFixture? paginatedArtists = await response.Content.ReadFromJsonAsync>(_jsonOptions); Assert.NotNull(paginatedArtists); ArtistResponse artist = Assert.Single(paginatedArtists!.Data); - Assert.Equal("Fellowship", artist.Name); + Assert.Equal("Fellowship", artist.Metadata.Name); Assert.Equal(1, paginatedArtists.Count); } @@ -126,7 +126,7 @@ public class GetArtistsEndpointTests : IClassFixture(content, _jsonOptions); Assert.NotNull(artistResponse); Assert.Equal(artistId, artistResponse!.Id); - Assert.Equal("Queen Updated", artistResponse.Name); + Assert.Equal("Queen Updated", artistResponse.Metadata.Name); using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -170,7 +171,7 @@ public class UpdateArtistEndpointTests : IClassFixture (language.LanguageCode, language.LanguageName, language.NativeName)).OrderBy(language => language.LanguageCode), + trackResponse.Work.Languages!.Select(language => (language.LanguageCode, language.LanguageName, language.NativeName)).OrderBy(language => language.LanguageCode)); + Assert.Equal( + trackRequest.Work.Iswcs!.OrderBy(iswc => iswc), + trackResponse.Work.Iswcs!.OrderBy(iswc => iswc)); Assert.Equal(trackRequest.MusicBrainzRecordingId, trackResponse.MusicBrainzRecordingId); Assert.Equal(trackRequest.MusicBrainzTrackId, trackResponse.MusicBrainzTrackId); - Assert.Equal(trackRequest.MusicBrainzWorkId, trackResponse.MusicBrainzWorkId); - // metadata checks + // Metadata checks. Assert.Equal(metadata.Title, trackResponse.Metadata.Title); Assert.Equal(metadata.OriginalTitle, trackResponse.Metadata.OriginalTitle); Assert.Equal(metadata.Description, trackResponse.Metadata.Description); @@ -184,7 +194,7 @@ public class AddTrackEndpointTests : IClassFixture genre.Name).OrderBy(name => name), trackResponse.Metadata.Genres!.Select(genre => genre.Name).OrderBy(name => name)); @@ -208,7 +218,7 @@ public class AddTrackEndpointTests : IClassFixture tag.Name).OrderBy(name => name), trackResponse.Metadata.Tags!.Select(tag => tag.Name).OrderBy(name => name)); - // moods, ISRCs, contributors and ratings checks + // Moods, ISRCs, contributors and ratings checks. Assert.Equal( trackRequest.Moods!.Select(mood => mood.Name).OrderBy(name => name), trackResponse.Moods!.Select(mood => mood.Name).OrderBy(name => name)); @@ -222,7 +232,7 @@ public class AddTrackEndpointTests : IClassFixture rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 4.5m && rating.MaxValue == 5 && rating.VoteCount == 2345); Assert.Contains(trackResponse.Ratings, rating => rating.Source == AudioRatingSource.LastFm && rating.Value == 4.8m && rating.MaxValue == 5 && rating.VoteCount == 1234); - // check Location header + // Check Location header. Assert.NotNull(response.Headers.Location); string locationUri = response.Headers.Location!.ToString(); Assert.EndsWith($"/api/v1/libraries/{_libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackResponse.Id}", locationUri); @@ -233,7 +243,7 @@ public class AddTrackEndpointTests : IClassFixture(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs new file mode 100644 index 00000000..621b5c40 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs @@ -0,0 +1,234 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryPathPartDefinitionResponseFixture _libraryPathPartDefinitionResponseFixture = new(); + private readonly LibraryPathTemplatePartResponseFixture _libraryPathTemplatePartResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryPathTemplatePartsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsMusic_ShouldReturnMusicCatalog() + { + // Arrange + List expectedParts = GetExpectedMusicParts(); + List expectedDefaultTemplateParts = GetExpectedMusicDefaultTemplateParts(); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Music"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(catalog); + Assert.Equal(10, catalog!.Parts.Count); + Assert.Equal(16, catalog.DefaultTemplateParts.Count); + Assert.Equal(expectedParts, catalog.Parts); + Assert.Equal(expectedDefaultTemplateParts, catalog.DefaultTemplateParts); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsBook_ShouldReturnBookCatalog() + { + // Arrange + List expectedParts = GetExpectedBookParts(); + List expectedDefaultTemplateParts = GetExpectedBookDefaultTemplateParts(); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Book"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(catalog); + Assert.Equal(8, catalog!.Parts.Count); + Assert.Equal(12, catalog.DefaultTemplateParts.Count); + Assert.Equal(expectedParts, catalog.Parts); + Assert.Equal(expectedDefaultTemplateParts, catalog.DefaultTemplateParts); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenLibraryTypeHasNoCatalog_ShouldReturnEmptyCatalog() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Movie"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(catalog); + Assert.Empty(catalog!.Parts); + Assert.Empty(catalog.DefaultTemplateParts); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult() + { + // Arrange + string libraryType = "NotARealLibraryType"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/path-template-parts/{libraryType}"); + + // Assert + // An unrecognized library type is a value that is not accepted, so it is reported as forbidden. + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(6, problemDetails!.Count); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("UnknownLibraryType", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/path-template-parts/{libraryType}", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Builds the exact path parts expected for a music library, as defined by MusicLibraryPathPartCatalog. + /// + /// The expected path parts, in catalog order. + private List GetExpectedMusicParts() + { + return + [ + _libraryPathPartDefinitionResponseFixture.Create(kind: "Literal", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Separator", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Artist", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseType", valueType: "Enum", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseYear", valueType: "Year", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseName", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "TrackNumber", valueType: "Integer", defaultRepresentation: "{0:00}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "TrackName", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Extension", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "DiscNumber", valueType: "Integer", defaultRepresentation: "{0:00}", isOptionalByDefault: true) + ]; + } + + /// + /// Builds the exact default template parts expected for a music library, as defined by MusicLibraryPathPartCatalog. + /// + /// The expected default template parts, in template order. + private List GetExpectedMusicDefaultTemplateParts() + { + return + [ + _libraryPathTemplatePartResponseFixture.Create(kind: "Artist", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseType", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseYear", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseName", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: true), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: "Disk ", isOptional: true), + _libraryPathTemplatePartResponseFixture.Create(kind: "DiscNumber", representation: "{0:00}", isOptional: true), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "TrackNumber", representation: "{0:00}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "TrackName", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ".", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Extension", representation: "{0}", isOptional: false) + ]; + } + + /// + /// Builds the exact path parts expected for a book library, as defined by BookLibraryPathPartCatalog. + /// + /// The expected path parts, in catalog order. + private List GetExpectedBookParts() + { + return + [ + _libraryPathPartDefinitionResponseFixture.Create(kind: "Literal", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Separator", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Author", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Title", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Series", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: true), + _libraryPathPartDefinitionResponseFixture.Create(kind: "SeriesNumber", valueType: "Integer", defaultRepresentation: "{0}", isOptionalByDefault: true), + _libraryPathPartDefinitionResponseFixture.Create(kind: "BookId", valueType: "Integer", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Extension", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false) + ]; + } + + /// + /// Builds the exact default template parts expected for a book library, as defined by BookLibraryPathPartCatalog. + /// + /// The expected default template parts, in template order. + private List GetExpectedBookDefaultTemplateParts() + { + return + [ + _libraryPathTemplatePartResponseFixture.Create(kind: "Author", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Title", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " (", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "BookId", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ")", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Title", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Author", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ".", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Extension", representation: "{0}", isOptional: false) + ]; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 5b2b614f..5f2b7c40 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -51,7 +51,7 @@ public class AddBookEndpointTests : IClassFixture PropertyNameCaseInsensitive = true, Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } }; - private readonly AddBookRequestFixture _requestBookFixture = new(); + private readonly AddBookRequestFixture _addBookRequestFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); @@ -95,7 +95,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidData_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); + AddBookRequest bookRequest = _addBookRequestFixture.Create(); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -200,7 +200,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -213,7 +213,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -226,7 +226,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalTitle_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act & Assert await AssertCreated(bookRequest); @@ -236,7 +236,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -249,7 +249,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyDescription_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); // Act & Assert await AssertCreated(bookRequest); @@ -259,7 +259,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthDescription_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -272,7 +272,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullReleaseInfo_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -285,7 +285,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseYear: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseYear: false))); // Act & Assert await AssertCreated(bookRequest); @@ -295,7 +295,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueOriginalReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -308,7 +308,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReReleaseYear: false, includeReReleaseDate: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReReleaseYear: false, includeReReleaseDate: false))); // Act & Assert await AssertCreated(bookRequest); @@ -318,7 +318,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -331,7 +331,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReleaseCountry_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseCountry: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseCountry: false))); // Act & Assert await AssertCreated(bookRequest); @@ -341,7 +341,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReleaseVersion_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); // Act & Assert await AssertCreated(bookRequest); @@ -351,7 +351,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReleasVersion_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(100)))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(100)))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -364,7 +364,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 2000, reReleaseDate: new DateOnly(2001, 1, 1), reReleaseYear: 2001))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 2000, reReleaseDate: new DateOnly(2001, 1, 1), reReleaseYear: 2001))); // Act & Assert await AssertCreated(bookRequest); @@ -374,7 +374,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsBeforeReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, reReleaseDate: new DateOnly(2000, 1, 1), reReleaseYear: 2000))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, reReleaseDate: new DateOnly(2000, 1, 1), reReleaseYear: 2000))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -387,7 +387,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 2000, reReleaseDate: new DateOnly(2001, 1, 1), reReleaseYear: 2001))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 2000, reReleaseDate: new DateOnly(2001, 1, 1), reReleaseYear: 2001))); // Act & Assert await AssertCreated(bookRequest); @@ -397,7 +397,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseDateIsBeforeReleaseDate_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, reReleaseDate: new DateOnly(2000, 1, 1), reReleaseYear: 2000))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, reReleaseDate: new DateOnly(2000, 1, 1), reReleaseYear: 2000))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -410,7 +410,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullGenres_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -423,7 +423,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGenreName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(includeName: false)])); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(includeName: false)])); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -436,7 +436,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthGenreName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(100))])); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(100))])); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -448,7 +448,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullTags_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -461,7 +461,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyTagName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(includeName: false)])); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(includeName: false)])); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -474,7 +474,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthTagName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(100))])); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(100))])); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -486,7 +486,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguage_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); // Act & Assert await AssertCreated(bookRequest); @@ -496,7 +496,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeLanguageCode: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeLanguageCode: false))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -509,7 +509,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(10)))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(10)))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -522,7 +522,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeLanguageName: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeLanguageName: false))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -535,7 +535,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(100)))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(100)))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -548,7 +548,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageNativeName_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act & Assert await AssertCreated(bookRequest); @@ -558,7 +558,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthNativeLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(100)))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(100)))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -571,7 +571,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguage_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act & Assert await AssertCreated(bookRequest); @@ -581,7 +581,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeLanguageCode: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeLanguageCode: false))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -594,7 +594,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(10)))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(10)))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -607,7 +607,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -620,7 +620,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(100)))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(100)))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -633,7 +633,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalNativeLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(100)))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(100)))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -646,7 +646,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageNativeName_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act & Assert await AssertCreated(bookRequest); @@ -656,7 +656,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyPublisher_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); // Act & Assert await AssertCreated(bookRequest); @@ -666,7 +666,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthPublisher_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(150))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(150))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -679,7 +679,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyPageCount_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); // Act & Assert await AssertCreated(bookRequest); @@ -689,7 +689,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativePageCount_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -702,7 +702,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyFormat_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -712,7 +712,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidFormat_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(format: (BookFormat)99); + AddBookRequest bookRequest = _addBookRequestFixture.Create(format: (BookFormat)99); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -725,7 +725,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyEdition_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -735,7 +735,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthEdition_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(edition: new Faker().Random.String2(100)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(edition: new Faker().Random.String2(100)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -748,7 +748,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyVolumeNumber_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -758,7 +758,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeVolumeNumber_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(volumeNumber: -1); + AddBookRequest bookRequest = _addBookRequestFixture.Create(volumeNumber: -1); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -771,7 +771,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptySeries_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); + AddBookRequest bookRequest = _addBookRequestFixture.Create(); // Act & Assert await AssertCreated(bookRequest); @@ -781,7 +781,7 @@ public class AddBookEndpointTests : IClassFixture //public async Task AddBook_WhenCalledWithEmptySeriesTitle_ShouldReturnUnprocessableEntity() //{ // // Arrange - // var bookRequest = _requestBookFixture.Create(); + // var bookRequest = _addBookRequestFixture.Create(); // bookRequest = bookRequest with // { // Series = bookRequest.Series! with { Title = null } @@ -798,7 +798,7 @@ public class AddBookEndpointTests : IClassFixture //public async Task AddBook_WhenCalledWithInvalidLengthSeriesTitle_ShouldReturnUnprocessableEntity() //{ // // Arrange - // var bookRequest = _requestBookFixture.Create(); + // var bookRequest = _addBookRequestFixture.Create(); // bookRequest = bookRequest with { Series = bookRequest.Series! with { Title = new Faker().Random.String2(300) } }; // // Act @@ -812,7 +812,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyAsin_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -822,7 +822,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthAsin_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(asin: new Faker().Random.String2(15)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(asin: new Faker().Random.String2(15)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -835,7 +835,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGoodreadsId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -845,7 +845,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidGoodreadsId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(goodreadsId: new Faker().Random.String2(2)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(goodreadsId: new Faker().Random.String2(2)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -858,7 +858,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLccn_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -868,7 +868,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLccn_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(lccn: new Faker().Random.String2(200)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(lccn: new Faker().Random.String2(200)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -881,7 +881,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOclcNumber_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -891,7 +891,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidOclcNumber_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: new Faker().Random.String2(200)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(oclcNumber: new Faker().Random.String2(200)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -904,7 +904,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOpenLibraryId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -914,7 +914,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidOpenLibraryId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(openLibraryId: new Faker().Random.String2(200)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(openLibraryId: new Faker().Random.String2(200)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -927,7 +927,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLibraryThingId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -937,7 +937,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(libraryThingId: new Faker().Random.String2(200)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(libraryThingId: new Faker().Random.String2(200)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -950,7 +950,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGoogleBooksId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -960,7 +960,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthGoogleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(googleBooksId: new Faker().Random.String2(20)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(googleBooksId: new Faker().Random.String2(20)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -973,7 +973,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidGoogleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); + AddBookRequest bookRequest = _addBookRequestFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -986,7 +986,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyBarnesAndNobleId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -996,7 +996,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(20)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(barnesAndNobleId: new Faker().Random.String2(20)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1009,7 +1009,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidBarnesAndNobleId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(10)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(barnesAndNobleId: new Faker().Random.String2(10)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1022,7 +1022,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [], contributors: [], ratings: [], includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false); // Act & Assert await AssertCreated(bookRequest); @@ -1032,7 +1032,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidAppleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(appleBooksId: new Faker().Random.String2(10)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(appleBooksId: new Faker().Random.String2(10)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1045,7 +1045,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullIsbns_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1058,7 +1058,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyIsbnValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1071,7 +1071,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbn10Value_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1084,7 +1084,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbn13Value_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1097,7 +1097,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbnFormat_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1109,7 +1109,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributors_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create() with { Contributors = null }; + AddBookRequest bookRequest = _addBookRequestFixture.Create() with { Contributors = null }; // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1122,7 +1122,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1135,7 +1135,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidContributorRole_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1148,7 +1148,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullRatings_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookRequest bookRequest = _addBookRequestFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1161,7 +1161,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeRatingValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -3)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -3)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1173,7 +1173,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 3, maxValue: 2)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 3, maxValue: 2)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1185,7 +1185,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeMaxRatingValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -3)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -3)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1197,7 +1197,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyRatingVoteCount_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(source: BookRatingSource.Goodreads, includeVoteCount: false)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(ratings: [_bookRatingDtoFixture.Create(source: BookRatingSource.Goodreads, includeVoteCount: false)]); // Act & Assert await AssertCreated(bookRequest); } @@ -1206,7 +1206,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeVoteCount_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -3)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -3)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1219,7 +1219,7 @@ public class AddBookEndpointTests : IClassFixture { // Arrange Guid contributorId = Guid.NewGuid(); - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: [ _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator) @@ -1251,7 +1251,7 @@ public class AddBookEndpointTests : IClassFixture { // Arrange string pathOutsideTheLibrary = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "..", "lumina-books-outside", $"{Guid.NewGuid():N}.epub")); - AddBookRequest bookRequest = _requestBookFixture.Create(path: pathOutsideTheLibrary); + AddBookRequest bookRequest = _addBookRequestFixture.Create(path: pathOutsideTheLibrary); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1264,7 +1264,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenBookPathAlreadyExistsInTheLibrary_ShouldReturnConflict() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); + AddBookRequest bookRequest = _addBookRequestFixture.Create(); // Act HttpResponseMessage firstResponse = await PostBookAsync(bookRequest); @@ -1286,7 +1286,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenAReferencedContributorDoesNotExist_ShouldReturnNotFound() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); // Act HttpResponseMessage response = await PostBookWithoutSeedingContributorsAsync(bookRequest); @@ -1306,7 +1306,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithTooLongPath_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1322,7 +1322,7 @@ public class AddBookEndpointTests : IClassFixture // only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync(); Guid missingLibraryId = Guid.NewGuid(); - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []); + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: []); // Act HttpResponseMessage response = await adminClient.PostAsJsonAsync($"/api/v1/libraries/{missingLibraryId}/books", bookRequest); @@ -1345,7 +1345,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenTitleIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1358,7 +1358,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenOriginalTitleIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1371,7 +1371,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenDescriptionIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1384,7 +1384,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenOriginalReleaseYearIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1397,7 +1397,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1410,7 +1410,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReleaseVersionIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1423,7 +1423,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenGenresAreValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1436,7 +1436,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenTagsAreValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1449,7 +1449,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidPublisher_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1462,7 +1462,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenPageCountIsPositive_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1475,7 +1475,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenFormatIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(format: BookFormat.Hardcover); + AddBookRequest bookRequest = _addBookRequestFixture.Create(format: BookFormat.Hardcover); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1488,7 +1488,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenEditionIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(edition: new Faker().Random.String2(50)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(edition: new Faker().Random.String2(50)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1501,7 +1501,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenVolumeNumberIsPositive_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(volumeNumber: 1); + AddBookRequest bookRequest = _addBookRequestFixture.Create(volumeNumber: 1); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1514,7 +1514,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenAsinIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(asin: new Faker().Random.String2(10)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(asin: new Faker().Random.String2(10)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1527,7 +1527,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenGoodreadsIdIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(goodreadsId: "123456789"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(goodreadsId: "123456789"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1540,7 +1540,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenLccnIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(lccn: "n78890351"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(lccn: "n78890351"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1553,7 +1553,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidOclcNumberFormat1_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "ocm12345678"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(oclcNumber: "ocm12345678"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1566,7 +1566,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidOclcNumberFormat2_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "ocn123456789"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(oclcNumber: "ocn123456789"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1579,7 +1579,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidOclcNumberFormat3_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "on1234567890"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(oclcNumber: "on1234567890"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1592,7 +1592,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidOclcNumberFormat4_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "(OCoLC)1234567890"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(oclcNumber: "(OCoLC)1234567890"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1605,7 +1605,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidOclcNumberFormat5_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "12345678"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(oclcNumber: "12345678"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1618,7 +1618,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenOpenLibraryIdIsValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(openLibraryId: "OL123456M"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(openLibraryId: "OL123456M"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1631,7 +1631,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidLibraryThingId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(libraryThingId: new Faker().Random.String2(50)); + AddBookRequest bookRequest = _addBookRequestFixture.Create(libraryThingId: new Faker().Random.String2(50)); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1644,7 +1644,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidGoogleBooksId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); + AddBookRequest bookRequest = _addBookRequestFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1657,7 +1657,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidBarnesAndNobleId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); + AddBookRequest bookRequest = _addBookRequestFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1670,7 +1670,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidAppleBooksId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(appleBooksId: "id123456"); + AddBookRequest bookRequest = _addBookRequestFixture.Create(appleBooksId: "id123456"); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1683,7 +1683,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidIsbn10_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1696,7 +1696,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidIsbn13_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1709,7 +1709,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenContributorsAreValid_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1722,7 +1722,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidRatings_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + AddBookRequest bookRequest = _addBookRequestFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); // Act HttpResponseMessage response = await PostBookAsync(bookRequest); @@ -1735,7 +1735,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []); + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: []); // Act HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/not-a-guid/books", bookRequest); @@ -1756,7 +1756,7 @@ public class AddBookEndpointTests : IClassFixture // Arrange HttpClient unauthenticatedClient = _apiFactory.CreateClient(); Guid libraryId = Guid.NewGuid(); - AddBookRequest request = _requestBookFixture.Create(contributors: []); + AddBookRequest request = _addBookRequestFixture.Create(contributors: []); // Act HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request); @@ -1769,7 +1769,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []); + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: []); using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); // Act & Assert @@ -1783,7 +1783,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []); + AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: []); using CancellationTokenSource cts = new(); // Act & Assert diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs index 41887801..72e69c41 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -54,7 +54,7 @@ public class UpdateBookEndpointTests : IClassFixture @@ -132,7 +132,7 @@ public class GetLibraryBookReadersEndpointTests : IClassFixture(); - dbContext.LibraryBookReaderConfigurations.Add(_configurationFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled)); + dbContext.LibraryBookReaderConfigurations.Add(_libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled)); await dbContext.SaveChangesAsync(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs index 102b2753..ad484e92 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs @@ -30,7 +30,7 @@ public class InstallPluginEndpointTests : IClassFixture _installedPluginFileNames = []; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -61,7 +61,7 @@ public class InstallPluginEndpointTests : IClassFixture @@ -61,7 +61,7 @@ public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture(); - dbContext.LibraryBookReaderConfigurations.Add(_configurationFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled)); + dbContext.LibraryBookReaderConfigurations.Add(_libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled)); await dbContext.SaveChangesAsync(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs index ab29125d..1ea66b9e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -34,7 +34,7 @@ public class DeleteThemeEndpointTests : IClassFixture _installedThemeIds = []; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -184,7 +184,7 @@ public class DeleteThemeEndpointTests : IClassFixture InstallThemeAsync() { string themeId = $"test-theme-{Guid.NewGuid():N}"; - byte[] archiveBytes = _themeArchiveFixture.Create(themeId); + byte[] archiveBytes = _testThemeArchiveFixture.Create(themeId); using MultipartFormDataContent multipartContent = []; using ByteArrayContent fileContent = new(archiveBytes); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs index 45e177aa..95866a37 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -36,7 +36,7 @@ public class InstallThemeEndpointTests : IClassFixture _installedThemeIds = []; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -67,7 +67,7 @@ public class InstallThemeEndpointTests : IClassFixture _installedThemeIds = []; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -184,7 +184,7 @@ public class RestoreThemeEndpointTests : IClassFixture InstallUserThemeAsync() { string themeId = $"test-theme-{Guid.NewGuid():N}"; - byte[] archiveBytes = _themeArchiveFixture.Create(themeId); + byte[] archiveBytes = _testThemeArchiveFixture.Create(themeId); using MultipartFormDataContent multipartContent = []; using ByteArrayContent fileContent = new(archiveBytes); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index ba576058..2a7b4ca0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; using Lumina.Contracts.Requests.Themes; using Lumina.Contracts.Responses.Themes; using Lumina.DataAccess.Core.UoW; @@ -34,7 +35,8 @@ public class SetCurrentThemeEndpointTests : IClassFixture _installedThemeIds = []; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -66,7 +68,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture InstallThemeAsync(string? themeId = null) { string resolvedThemeId = themeId ?? $"test-theme-{Guid.NewGuid():N}"; - byte[] archiveBytes = _themeArchiveFixture.Create(resolvedThemeId); + byte[] archiveBytes = _testThemeArchiveFixture.Create(resolvedThemeId); using MultipartFormDataContent multipartContent = []; using ByteArrayContent fileContent = new(archiveBytes); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index 4540b00a..ee74e477 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -37,6 +38,7 @@ public class RecoverPasswordEndpointTests : IClassFixturenet10.0 disable enable - false true diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index 2bf639fd..5c7999bc 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Themes; -using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; using System; @@ -25,6 +25,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -45,7 +46,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme") { - Content = JsonContent.Create(new SetCurrentThemeRequest(THEME_ID)) + Content = JsonContent.Create(_setCurrentThemeRequestFixture.Create(themeId: THEME_ID)) }; setCurrentThemeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); setCurrentThemeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs index 25f4a8bb..11aa7902 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs @@ -24,7 +24,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage public class SetBookReaderEnabledEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; - private readonly SetBookReaderEnabledRequestFixture _requestFixture = new(); + private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +42,7 @@ public class SetBookReaderEnabledEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); Guid pluginId = Guid.NewGuid(); - SetBookReaderEnabledRequest request = _requestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); + SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); string expectedEndpoint = $"libraries/{libraryId}/book-readers/{pluginId}/enabled"; _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new EmptyRequest()); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); @@ -71,7 +71,7 @@ public class SetBookReaderEnabledEndpointTests : IClassFixture { // Arrange HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); - SetBookReaderEnabledRequest request = _requestFixture.Create(); + SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") { Content = JsonContent.Create(request) diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj index 58fd7084..be102554 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs b/tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Core/CalibreArtworkProviderSecurityTests.cs similarity index 88% rename from tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs rename to tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Core/CalibreArtworkProviderSecurityTests.cs index 8dc6371d..442ee77f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs +++ b/tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Core/CalibreArtworkProviderSecurityTests.cs @@ -4,10 +4,15 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book using Lumina.Plugins.Calibre.Core; using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre; +namespace Lumina.Plugins.Calibre.SecurityTests.Core; /// /// Contains security tests for the class, exercised through the public artwork provider surface. @@ -29,11 +34,11 @@ public class CalibreArtworkProviderSecurityTests IArtworkProvider provider = CreateArtworkProvider(); // Act - ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + IReadOnlyList result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); // Assert - Assert.NotNull(result); - Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), artwork.LocalPath); } finally { @@ -60,10 +65,10 @@ public class CalibreArtworkProviderSecurityTests IArtworkProvider provider = CreateArtworkProvider(); // Act - ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + IReadOnlyList result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs b/tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Core/Opf/OpfReaderSecurityTests.cs similarity index 96% rename from tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs rename to tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Core/Opf/OpfReaderSecurityTests.cs index 9930968d..20904f19 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs +++ b/tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Core/Opf/OpfReaderSecurityTests.cs @@ -6,10 +6,14 @@ using Lumina.Plugins.Calibre.Core; using Lumina.Plugins.Calibre.Core.Opf; using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; +using System; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre.Opf; +namespace Lumina.Plugins.Calibre.SecurityTests.Core.Opf; /// /// Contains security tests for the class, exercised through the public metadata provider surface. @@ -27,7 +31,7 @@ public class OpfReaderSecurityTests string bookDirectory = CreateTempDirectory(); try { - // the OPF is untrusted XML, so a DTD with an external entity must be rejected instead of being read and expanded + // The OPF is untrusted XML, so a DTD with an external entity must be rejected instead of being read and expanded. string opfContent = """]>&xxe;"""; string bookPath = WriteBookWithOpf(bookDirectory, opfContent); IMetadataProvider provider = CreateMetadataProvider(); diff --git a/tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Lumina.Plugins.Calibre.SecurityTests.csproj b/tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Lumina.Plugins.Calibre.SecurityTests.csproj new file mode 100644 index 00000000..a5cba043 --- /dev/null +++ b/tests/SecurityTests/Lumina.Plugins.Calibre.SecurityTests/Lumina.Plugins.Calibre.SecurityTests.csproj @@ -0,0 +1,47 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Api/CoverArtArchiveHttpClientSecurityTests.cs b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Api/CoverArtArchiveHttpClientSecurityTests.cs new file mode 100644 index 00000000..6b2dcf25 --- /dev/null +++ b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Api/CoverArtArchiveHttpClientSecurityTests.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.CoverArtArchive.Core; +using Lumina.Plugins.CoverArtArchive.Core.Api; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.SecurityTests.Core.Api; + +/// +/// Contains security tests for the class, exercised through the requests it sends. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveHttpClientSecurityTests +{ + private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + + private readonly CoverArtArchiveSettingsDtoFixture _coverArtArchiveSettingsDtoFixture = new(); + + [Theory] + [InlineData("https://evil.example/index.json")] // an unrelated public host + [InlineData("https://localhost/index.json")] // the loopback host name + [InlineData("https://127.0.0.1/index.json")] // the IPv4 loopback address + [InlineData("https://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint + [InlineData("https://10.0.0.5/index.json")] // a private class A address + [InlineData("https://192.168.1.10/index.json")] // a private class C address + [InlineData("https://coverartarchive.org.evil.example/index.json")] // the trusted host used as a prefix of an attacker controlled host + public async Task GetReleaseArtworkAsync_WhenTheRedirectPointsAtADisallowedHost_ShouldThrowAndNotReachIt(string location) + { + // Arrange + CapturingHttpMessageHandler handler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri(location); + return redirect; + }); + CoverArtArchiveHttpClient sut = CreateClient(handler); + + // Act + Task Act() + { + return sut.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + // No request is ever sent to the disallowed host, the client only ever talks to the Cover Art Archive. + Assert.All(handler.Requests, request => Assert.Equal("coverartarchive.org", request.RequestUri!.Host)); + } + + [Theory] + [InlineData("http://archive.org/index.json")] // a downgrade of the Internet Archive to plain HTTP + [InlineData("http://coverartarchive.org/index.json")] // a downgrade of the Cover Art Archive to plain HTTP + public async Task GetReleaseArtworkAsync_WhenTheRedirectDowngradesToPlainHttp_ShouldThrow(string location) + { + // Arrange + CapturingHttpMessageHandler handler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri(location); + return redirect; + }); + CoverArtArchiveHttpClient sut = CreateClient(handler); + + // Act + Task Act() + { + return sut.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Theory] + [InlineData("user@example.com\r\nX-Injected: value")] // carriage return and line feed header injection + [InlineData("user@example.com\nX-Injected: value")] // line feed header injection + public async Task GetReleaseArtworkAsync_WhenThePersistedContactEmailAttemptsHeaderInjection_ShouldNotInjectAnyHeader(string maliciousEmail) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [CoverArtArchiveSettingsKeys.CONTACT_EMAIL] = maliciousEmail }); + CoverArtArchiveSettingsProvider settingsProvider = new(mockStore, CoverArtArchivePlugin.s_pluginId, _coverArtArchiveSettingsDtoFixture.Create( + userAgent: "Lumina-Security/1.0", + includeContactEmail: false, + minimumRequestInterval: TimeSpan.Zero)); + CapturingHttpMessageHandler handler = new((request, callIndex) => CreateJsonResponse("""{"images":[]}""")); + CoverArtArchiveHttpClient sut = new(new HttpClient(handler), settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache()); + + // Act + await sut.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + HttpRequestMessage request = Assert.Single(handler.Requests); + Assert.Equal("Lumina-Security/1.0", request.Headers.UserAgent.ToString()); + Assert.False(request.Headers.Contains("X-Injected")); + } + + /// + /// Creates a that sends its requests through the provided handler, with no throttling. + /// + /// The handler that answers the requests of the client. + /// The created client. + private CoverArtArchiveHttpClient CreateClient(HttpMessageHandler handler) + { + CoverArtArchiveSettingsProvider settingsProvider = new(null, CoverArtArchivePlugin.s_pluginId, _coverArtArchiveSettingsDtoFixture.Create( + userAgent: "Lumina-Security/1.0", + includeContactEmail: false, + minimumRequestInterval: TimeSpan.Zero)); + return new CoverArtArchiveHttpClient(new HttpClient(handler), settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache()); + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage CreateJsonResponse(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } + + /// + /// HTTP message handler that answers every request through a factory and records the requests that were sent. + /// + [ExcludeFromCodeCoverage] + private sealed class CapturingHttpMessageHandler : HttpMessageHandler + { + private readonly Func _responseFactory; + private int _callCount; + + /// + /// Gets the requests that were sent through the handler. + /// + public List Requests { get; } = []; + + /// + /// Initializes a new instance of the class. + /// + /// The factory that produces the response of a request, given the request and its one based call index. + public CapturingHttpMessageHandler(Func responseFactory) + { + _responseFactory = responseFactory; + } + + /// + /// Answers the provided request through the configured factory. + /// + /// The request to answer. + /// Cancellation token that can be used to stop the execution. + /// The response to the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + int callIndex = Interlocked.Increment(ref _callCount); + Requests.Add(request); + return Task.FromResult(_responseFactory(request, callIndex)); + } + } +} diff --git a/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Mapping/CoverArtArchiveMapperSecurityTests.cs b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Mapping/CoverArtArchiveMapperSecurityTests.cs new file mode 100644 index 00000000..7ade7a53 --- /dev/null +++ b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Core/Mapping/CoverArtArchiveMapperSecurityTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using Lumina.Plugins.CoverArtArchive.Core.Mapping; +using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.Contracts.Responses; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.SecurityTests.Core.Mapping; + +/// +/// Contains security tests for the class, exercised through the artwork it emits. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveMapperSecurityTests +{ + private readonly CoverArtArchiveArtworkResponseFixture _coverArtArchiveArtworkResponseFixture = new(); + private readonly CoverArtArchiveImageResponseFixture _coverArtArchiveImageResponseFixture = new(); + + [Theory] + [InlineData("http://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint + [InlineData("http://localhost/admin")] // the loopback host name + [InlineData("http://127.0.0.1/admin")] // the IPv4 loopback address + [InlineData("http://[::1]/admin")] // the IPv6 loopback address + [InlineData("http://10.0.0.5/internal")] // a private class A address + [InlineData("http://172.16.0.1/internal")] // a private class B address + [InlineData("http://192.168.1.10/internal")] // a private class C address + [InlineData("http://0.0.0.0/internal")] // the unspecified address + [InlineData("http://[fc00::1]/internal")] // the IPv6 unique local range + [InlineData("https://evil.example/tracker.jpg")] // an unrelated public host + [InlineData("https://coverartarchive.org.evil.example/1.jpg")] // the trusted host used as a prefix of an attacker controlled host + [InlineData("https://archive.org.evil.example/1.jpg")] // the Internet Archive host used as a prefix of an attacker controlled host + public void MapArtwork_WhenAnImageUrlPointsAtAnInternalOrUntrustedHost_ShouldDropIt(string maliciousUrl) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: maliciousUrl, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData("file:///etc/passwd")] // a local file URI + [InlineData("ftp://coverartarchive.org/1.jpg")] // a non web scheme + [InlineData("javascript:alert(1)")] // a script scheme + [InlineData("data:image/png;base64,SGVsbG8=")] // an inline data URI + public void MapArtwork_WhenAnImageUrlUsesAnUnsupportedScheme_ShouldDropIt(string maliciousUrl) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: maliciousUrl, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg")] // a trusted Cover Art Archive image + [InlineData("https://archive.org/download/mbid-11111111-1111-1111-1111-111111111111/front.jpg")] // a trusted Internet Archive image + public void MapArtwork_WhenAnImageUrlPointsAtATrustedHostOverHttps_ShouldKeepIt(string trustedUrl) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: trustedUrl, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(trustedUrl, artwork.RemoteUrl); + } + + [Fact] + public void MapArtwork_WhenAnImageUrlPointsAtATrustedHostOverPlainHttp_ShouldUpgradeItToHttps() + { + // Arrange + const string HTTP_URL = "http://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg"; + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: HTTP_URL, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", artwork.RemoteUrl); + } +} diff --git a/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests.csproj b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests.csproj new file mode 100644 index 00000000..96c1afee --- /dev/null +++ b/tests/SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests/Lumina.Plugins.CoverArtArchive.SecurityTests.csproj @@ -0,0 +1,47 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests/Core/Api/MusicBrainzHttpClientSecurityTests.cs b/tests/SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests/Core/Api/MusicBrainzHttpClientSecurityTests.cs new file mode 100644 index 00000000..9a259e73 --- /dev/null +++ b/tests/SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests/Core/Api/MusicBrainzHttpClientSecurityTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.SecurityTests.Core.Api; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzHttpClientSecurityTests +{ + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Theory] + [InlineData("A & B")] // ampersand query separator + [InlineData("Title #fragment")] // fragment separator + [InlineData("A?B")] // query separator + [InlineData("../../secret")] // path traversal + [InlineData("A\" OR \"B")] // quote escape + [InlineData("A\0B")] // null byte truncation + public async Task SearchArtistsAsync_WhenTheQueryContainsInjectionCharacters_ShouldNotAlterTheRequestTarget(string maliciousQuery) + { + // Arrange + CapturingHttpMessageHandler handler = new("""{"artists":[]}"""); + MusicBrainzHttpClient sut = CreateClient(handler); + + // Act + await sut.SearchArtistsAsync(maliciousQuery, 10, CancellationToken.None); + + // Assert + Uri requestUri = Assert.Single(handler.Requests).RequestUri!; + Assert.Equal("musicbrainz.example", requestUri.Host); + Assert.Equal("/ws/2/artist", requestUri.AbsolutePath); + Assert.Equal(string.Empty, requestUri.Fragment); + } + + [Theory] + [InlineData("../release/secret")] // path traversal + [InlineData("A&B")] // query separator + [InlineData("A#B")] // fragment separator + public async Task GetRecordingsByIsrcAsync_WhenTheIsrcContainsInjectionCharacters_ShouldNotAlterTheRequestTarget(string maliciousIsrc) + { + // Arrange + CapturingHttpMessageHandler handler = new("""{"recordings":[]}"""); + MusicBrainzHttpClient sut = CreateClient(handler); + + // Act + await sut.GetRecordingsByIsrcAsync(maliciousIsrc, CancellationToken.None); + + // Assert + Uri requestUri = Assert.Single(handler.Requests).RequestUri!; + Assert.Equal("musicbrainz.example", requestUri.Host); + Assert.StartsWith("/ws/2/isrc/", requestUri.AbsolutePath); + Assert.Equal(string.Empty, requestUri.Fragment); + } + + /// + /// Creates a that points at a test host and sends its requests through the provided handler. + /// + /// The handler that answers the requests of the client. + /// The created client. + private MusicBrainzHttpClient CreateClient(HttpMessageHandler handler) + { + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: "http://musicbrainz.example/ws/2/", + userAgent: "Lumina-Test/1.0", + includeContactEmail: false, + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.Zero)); + return new MusicBrainzHttpClient(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + } + + /// + /// HTTP message handler that answers every request with a canned JSON body and records the requests that were sent. + /// + [ExcludeFromCodeCoverage] + private sealed class CapturingHttpMessageHandler : HttpMessageHandler + { + private readonly string _json; + + /// + /// Gets the requests that were sent through the handler. + /// + public List Requests { get; } = []; + + /// + /// Initializes a new instance of the class. + /// + /// The JSON body answered to every request. + public CapturingHttpMessageHandler(string json) + { + _json = json; + } + + /// + /// Answers the provided request with the canned JSON body. + /// + /// The request to answer. + /// Cancellation token that can be used to stop the execution. + /// The response to the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(_json, Encoding.UTF8, "application/json") + }); + } + } +} diff --git a/tests/SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests.csproj b/tests/SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests.csproj new file mode 100644 index 00000000..0026b68f --- /dev/null +++ b/tests/SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests/Lumina.Plugins.MusicBrainz.SecurityTests.csproj @@ -0,0 +1,47 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs index c3d08c2c..efa5fbb0 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs @@ -33,7 +33,7 @@ public class AddAlbumEndpointTests : IClassFixture, IDisposabl private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); @@ -158,7 +158,7 @@ public class AddAlbumEndpointTests : IClassFixture, IDisposabl _seededUsernames.Add(username); (Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(userId); AddAlbumRequest request = _addAlbumRequestFixture.Create( - metadata: _albumMetadataDtoFixture.Create(title: maliciousTitle), + metadata: _musicAlbumMetadataDtoFixture.Create(title: maliciousTitle), contributors: [], ratings: [], tracks: []); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs index 15190c19..22bec8c6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs @@ -33,7 +33,7 @@ public class UpdateAlbumEndpointTests : IClassFixture, IDispos { private readonly LuminaApiFactory _apiFactory; private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); @@ -104,7 +104,7 @@ public class UpdateAlbumEndpointTests : IClassFixture, IDispos (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); _seededUsernames.Add(username); (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId); - UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: maliciousTitle), contributors: [], ratings: []); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: maliciousTitle), contributors: [], ratings: []); // Act HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request); @@ -223,7 +223,7 @@ public class UpdateAlbumEndpointTests : IClassFixture, IDispos (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); _seededUsernames.Add(victimUsername); (_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndAlbumAsync(victimUserId); - UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: "Hijacked"), contributors: [], ratings: []); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: "Hijacked"), contributors: [], ratings: []); // Act HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}", request); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs index 42a97d3b..23cf6b48 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; @@ -34,6 +35,7 @@ public class AddArtistEndpointTests : IClassFixture, IDisposab private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly AddArtistRequestFixture _addArtistRequestFixture = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() @@ -58,7 +60,7 @@ public class AddArtistEndpointTests : IClassFixture, IDisposab { // Arrange Guid libraryId = Guid.NewGuid(); - AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: []); // Act HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request); @@ -80,7 +82,7 @@ public class AddArtistEndpointTests : IClassFixture, IDisposab public async Task AddArtist_WhenUnauthorized_ShouldNotLeakSensitiveData() { // Arrange - AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: []); // Act HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists", request); @@ -103,7 +105,7 @@ public class AddArtistEndpointTests : IClassFixture, IDisposab // Arrange (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); _seededUsernames.Add(username); - AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: []); // Act HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists", request); @@ -130,7 +132,7 @@ public class AddArtistEndpointTests : IClassFixture, IDisposab _seededUsernames.Add(username); Guid libraryId = await SeedLibraryAsync(userId); AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); - AddArtistRequest request = _addArtistRequestFixture.Create(name: maliciousName, contributors: [], albums: [album]); + AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: maliciousName), contributors: [], albums: [album]); // Act HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request); @@ -159,7 +161,7 @@ public class AddArtistEndpointTests : IClassFixture, IDisposab (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); _seededUsernames.Add(requesterUsername); AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); - AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: [album]); + AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]); // Act HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs index 909cc08b..c73a891b 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs @@ -33,8 +33,9 @@ public class UpdateArtistEndpointTests : IClassFixture, IDispo { private readonly LuminaApiFactory _apiFactory; private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); @@ -107,11 +108,11 @@ public class UpdateArtistEndpointTests : IClassFixture, IDispo (Guid artistId, Guid albumId) = await SeedArtistAsync(libraryId, userId); UpdateArtistAlbumRequest album = _updateArtistAlbumRequestFixture.Create( albumId: albumId, - metadata: _albumMetadataDtoFixture.Create(title: "Updated Album"), + metadata: _musicAlbumMetadataDtoFixture.Create(title: "Updated Album"), contributors: [], ratings: [], tracks: []); - UpdateArtistRequest request = _updateArtistRequestFixture.Create(name: maliciousName, contributors: [], albums: [album]); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: maliciousName), contributors: [], albums: [album]); // Act HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request); @@ -240,7 +241,7 @@ public class UpdateArtistEndpointTests : IClassFixture, IDispo _seededUsernames.Add(victimUsername); Guid victimLibraryId = Guid.NewGuid(); (Guid victimArtistId, _) = await SeedArtistAsync(victimLibraryId, victimUserId); - UpdateArtistRequest request = _updateArtistRequestFixture.Create(name: "Hijacked", contributors: [], albums: []); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Hijacked"), contributors: [], albums: []); // Act HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}", request); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs index 614bd079..07d1d272 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs @@ -33,7 +33,7 @@ public class AddTrackEndpointTests : IClassFixture, IDisposabl private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly AddTrackRequestFixture _addTrackRequestFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); @@ -201,7 +201,7 @@ public class AddTrackEndpointTests : IClassFixture, IDisposabl (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId); AddTrackRequest request = _addTrackRequestFixture.Create( path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.flac"), - metadata: _audioMetadataDtoFixture.Create(title: maliciousTitle), + metadata: _musicTrackMetadataDtoFixture.Create(title: maliciousTitle), contributors: []); // Act diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs index 564d78e4..eafa1ec8 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs @@ -37,7 +37,7 @@ public class UpdateTrackEndpointTests : IClassFixture, IDispos private readonly LuminaApiFactory _apiFactory; private readonly UpdateTrackRequestFixture _updateTrackRequestFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly TrackEntityFixture _trackEntityFixture = new(); @@ -95,7 +95,7 @@ public class UpdateTrackEndpointTests : IClassFixture, IDispos (Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId); UpdateTrackRequest request = _updateTrackRequestFixture.Create( path: Path.Combine(s_contentRootPath, $"injected-{Guid.NewGuid():N}.flac"), - metadata: _audioMetadataDtoFixture.Create(title: maliciousTitle), + metadata: _musicTrackMetadataDtoFixture.Create(title: maliciousTitle), moods: [], isrcs: [], contributors: [], @@ -263,7 +263,7 @@ public class UpdateTrackEndpointTests : IClassFixture, IDispos Guid victimLibraryId = Guid.NewGuid(); SeedLibrary(victimLibraryId, victimUserId); (Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = SeedArtistGraph(victimLibraryId); - UpdateTrackRequest request = _updateTrackRequestFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: "Hijacked")); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: "Hijacked")); // Act HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}", request); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs new file mode 100644 index 00000000..d51a5d5a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryPathTemplatePartsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryType = "Music"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/path-template-parts/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/path-template-parts/{libraryType}", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Libraries--")] // destructive SQL injection + [InlineData("Music; rm -rf /")] // command injection + [InlineData("$(whoami)")] // command substitution injection + [InlineData("`whoami`")] // backtick command injection + [InlineData("{0}{1}{0}")] // template/placeholder injection + [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // windows path traversal + [InlineData("%2e%2e%2fetc%2fpasswd")] // encoded path traversal + public async Task GetLibraryPathTemplateParts_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/path-template-parts/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // An unrecognized library type is a value that is not accepted, so it is reported as forbidden, and the response must stay + // generic: the failed request leaks no database, filesystem or framework internals. + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(6, problemDetails!.Count); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("UnknownLibraryType", problemDetails["detail"].GetString()); + Assert.StartsWith("/api/v1/libraries/path-template-parts/", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs index 45e65524..8a5ccf4c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs @@ -22,7 +22,7 @@ public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -39,7 +39,7 @@ public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture, IDi { private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; + private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -39,7 +41,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture, IDi public async Task SetCurrentTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange - SetCurrentThemeRequest request = new("some-theme"); + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(themeId: "some-theme"); // Act HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", request); @@ -64,7 +66,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture, IDi // Arrange HttpClient client = _apiFactory.CreateClient(); await _apiFactory.CreateAndAuthenticateUserAsync(client); - SetCurrentThemeRequest request = new("some-theme"); + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(themeId: "some-theme"); // Act HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/themes/current", request); @@ -96,7 +98,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture, IDi // Arrange HttpClient client = _apiFactory.CreateClient(); await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - SetCurrentThemeRequest request = new(maliciousThemeId); + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(themeId: maliciousThemeId); // Act HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/themes/current", request); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs index 10880ed1..7dfc8702 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs @@ -30,6 +30,7 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis private readonly PasswordHashService _hashService = new(); private readonly UserEntityFixture _userEntityFixture = new(); private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); private readonly string _testUsername; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -165,9 +166,10 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis await dbContext.SaveChangesAsync(); // Authenticate user. - LoginRequest loginRequest = new( - Username: user.Username, - Password: "TestPass123!" + LoginRequest loginRequest = _loginRequestFixture.Create( + username: user.Username, + password: "TestPass123!", + includeTotpCode: false ); HttpResponseMessage loginResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", loginRequest); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index 0da62077..c8857b5f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; @@ -32,6 +33,7 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi private readonly HttpClient _client; private readonly PasswordHashService _hashService = new(); private readonly UserEntityFixture _userEntityFixture = new(); + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -57,9 +59,9 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi public async Task RecoverPassword_WhenRateLimitExceeded_ShouldReturnTooManyRequests() { // Arrange - RecoverPasswordRequest request = new( - Username: "testuser", - TotpCode: "123456" + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create( + username: "testuser", + totpCode: "123456" ); // Act @@ -97,9 +99,9 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); UserEntity legitimateUser = await CreateTestUser(); - RecoverPasswordRequest request = new( - Username: maliciousUsername, - TotpCode: "123456" + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create( + username: maliciousUsername, + totpCode: "123456" ); // Act diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs index 364d4351..169819d2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs @@ -120,8 +120,8 @@ public class BookArtworkServiceSecurityTests string capturedDestinationPath = string.Empty; _mockFileProviderService.CopyFile(Arg.Any(), Arg.Do(destination => capturedDestinationPath = destination.Path), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") - .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpeg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg")))); // Act char separator = Path.DirectorySeparatorChar; diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj index c4b45279..6894b4c7 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj @@ -4,7 +4,6 @@ net10.0 enable enable - false true @@ -42,7 +41,6 @@ - diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index 81821d49..41a8a103 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -18,6 +18,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.SetC public class SetCurrentThemeEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -67,11 +68,11 @@ public class SetCurrentThemeEndpointTests : IClassFixture /// Builds a PUT request for the set current theme route with the JSON content type required by the antiforgery validation. /// /// The configured PUT request. - private static HttpRequestMessage CreateSetCurrentThemeRequest() + private HttpRequestMessage CreateSetCurrentThemeRequest() { HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme") { - Content = JsonContent.Create(new SetCurrentThemeRequest("test-theme")) + Content = JsonContent.Create(_setCurrentThemeRequestFixture.Create(themeId: "test-theme")) }; setCurrentThemeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); setCurrentThemeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs index 77943547..add45a9f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs @@ -22,7 +22,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen public class SetBookReaderEnabledEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; - private readonly SetBookReaderEnabledRequestFixture _requestFixture = new(); + private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -38,7 +38,7 @@ public class SetBookReaderEnabledEndpointTests : IClassFixture { // Arrange HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); - SetBookReaderEnabledRequest request = _requestFixture.Create(); + SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") { Content = JsonContent.Create(request) @@ -59,7 +59,7 @@ public class SetBookReaderEnabledEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - SetBookReaderEnabledRequest request = _requestFixture.Create(); + SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") { Content = JsonContent.Create(request) diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj index c8640d07..abf58b9d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj @@ -4,7 +4,6 @@ net10.0 enable enable - false true diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs index 5d0544b9..eff3c450 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs @@ -14,13 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; [ExcludeFromCodeCoverage] public class ChangePasswordRequestMappingTests { - private readonly ChangePasswordRequestFixture _fixture = new(); + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); [Fact] public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - ChangePasswordRequest request = _fixture.Create(); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); // Act ChangePasswordCommand result = request.ToCommand(); @@ -37,7 +37,7 @@ public class ChangePasswordRequestMappingTests public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() { // Arrange - ChangePasswordRequest request = new(null, null, null, null); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(includeUsername: false, includeCurrentPassword: false, includeNewPassword: false, includeNewPasswordConfirm: false); // Act ChangePasswordCommand result = request.ToCommand(); @@ -61,7 +61,15 @@ public class ChangePasswordRequestMappingTests string? newPasswordConfirm) { // Arrange - ChangePasswordRequest request = new(username, currentPassword, newPassword, newPasswordConfirm); + ChangePasswordRequest request = _changePasswordRequestFixture.Create( + username, + currentPassword, + newPassword, + newPasswordConfirm, + includeUsername: username is not null, + includeCurrentPassword: currentPassword is not null, + includeNewPassword: newPassword is not null, + includeNewPasswordConfirm: newPasswordConfirm is not null); // Act ChangePasswordCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs index 5e2a7705..23288821 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs @@ -14,13 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; [ExcludeFromCodeCoverage] public class LoginRequestMappingTests { - private readonly LoginRequestFixture _fixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); [Fact] public void ToQuery_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - LoginRequest request = _fixture.Create(); + LoginRequest request = _loginRequestFixture.Create(); // Act LoginUserQuery result = request.ToQuery(); @@ -36,7 +36,7 @@ public class LoginRequestMappingTests public void ToQuery_WhenMappingRequestWithNullValues_ShouldMapCorrectly() { // Arrange - LoginRequest request = new(null, null); + LoginRequest request = _loginRequestFixture.Create(includeUsername: false, includePassword: false, includeTotpCode: false); // Act LoginUserQuery result = request.ToQuery(); @@ -59,7 +59,13 @@ public class LoginRequestMappingTests string? totpCode) { // Arrange - LoginRequest request = new(username, password, totpCode); + LoginRequest request = _loginRequestFixture.Create( + username, + password, + totpCode, + includeUsername: username is not null, + includePassword: password is not null, + includeTotpCode: totpCode is not null); // Act LoginUserQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs index 2191d1eb..c68d50ac 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs @@ -14,13 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; [ExcludeFromCodeCoverage] public class RecoverPasswordRequestMappingTests { - private readonly RecoverPasswordRequestFixture _fixture = new(); + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); [Fact] public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - RecoverPasswordRequest request = _fixture.Create(); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); // Act RecoverPasswordCommand result = request.ToCommand(); @@ -35,7 +35,7 @@ public class RecoverPasswordRequestMappingTests public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() { // Arrange - RecoverPasswordRequest request = new(null, null); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(includeUsername: false, includeTotpCode: false); // Act RecoverPasswordCommand result = request.ToCommand(); @@ -56,7 +56,11 @@ public class RecoverPasswordRequestMappingTests string? totpCode) { // Arrange - RecoverPasswordRequest request = new(username, totpCode); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create( + username, + totpCode, + includeUsername: username is not null, + includeTotpCode: totpCode is not null); // Act RecoverPasswordCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs index 414607f3..de3d3c05 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs @@ -15,13 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; [ExcludeFromCodeCoverage] public class RegistrationRequestMappingTests { - private readonly RegistrationRequestFixture _fixture = new(); + private readonly RegistrationRequestFixture _registrationRequestFixture = new(); [Fact] public void ToSetupCommand_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - RegistrationRequest request = _fixture.Create(); + RegistrationRequest request = _registrationRequestFixture.Create(); // Act SetupApplicationCommand result = request.ToSetupCommand(); @@ -38,7 +38,7 @@ public class RegistrationRequestMappingTests public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - RegistrationRequest request = _fixture.Create(); + RegistrationRequest request = _registrationRequestFixture.Create(); // Act RegisterUserCommand result = request.ToCommand(); @@ -55,7 +55,7 @@ public class RegistrationRequestMappingTests public void ToSetupCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() { // Arrange - RegistrationRequest request = new(); + RegistrationRequest request = _registrationRequestFixture.Create(includeUsername: false, includePassword: false, includePasswordConfirm: false, use2fa: true); // Act SetupApplicationCommand result = request.ToSetupCommand(); @@ -72,7 +72,7 @@ public class RegistrationRequestMappingTests public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() { // Arrange - RegistrationRequest request = new(); + RegistrationRequest request = _registrationRequestFixture.Create(includeUsername: false, includePassword: false, includePasswordConfirm: false, use2fa: true); // Act RegisterUserCommand result = request.ToCommand(); @@ -97,7 +97,14 @@ public class RegistrationRequestMappingTests bool use2fa) { // Arrange - RegistrationRequest request = new(username, password, passwordConfirm, use2fa); + RegistrationRequest request = _registrationRequestFixture.Create( + username, + password, + passwordConfirm, + use2fa, + includeUsername: username is not null, + includePassword: password is not null, + includePasswordConfirm: passwordConfirm is not null); // Act SetupApplicationCommand result = request.ToSetupCommand(); @@ -122,7 +129,14 @@ public class RegistrationRequestMappingTests bool use2fa) { // Arrange - RegistrationRequest request = new(username, password, passwordConfirm, use2fa); + RegistrationRequest request = _registrationRequestFixture.Create( + username, + password, + passwordConfirm, + use2fa, + includeUsername: username is not null, + includePassword: password is not null, + includePasswordConfirm: passwordConfirm is not null); // Act RegisterUserCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/AddRoleRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/AddRoleRequestMappingTests.cs index 3a82672c..2e115e13 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/AddRoleRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/AddRoleRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System; using System.Collections.Generic; @@ -15,11 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class AddRoleRequestMappingTests { + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - AddRoleRequest request = new( + AddRoleRequest request = _addRoleRequestFixture.Create( "Admin", [Guid.NewGuid(), Guid.NewGuid()] ); @@ -37,7 +40,7 @@ public class AddRoleRequestMappingTests public void ToCommand_WhenMappingRequestWithEmptyPermissions_ShouldMapCorrectly() { // Arrange - AddRoleRequest request = new( + AddRoleRequest request = _addRoleRequestFixture.Create( "Guest", [] ); @@ -58,7 +61,7 @@ public class AddRoleRequestMappingTests public void ToCommand_WhenMappingDifferentRoleNames_ShouldMapCorrectly(string roleName) { // Arrange - AddRoleRequest request = new( + AddRoleRequest request = _addRoleRequestFixture.Create( roleName, [Guid.NewGuid()] ); @@ -82,7 +85,7 @@ public class AddRoleRequestMappingTests Guid.Parse("00000000-0000-0000-0000-000000000002"), Guid.Parse("00000000-0000-0000-0000-000000000003") ]; - AddRoleRequest request = new("SuperAdmin", permissions); + AddRoleRequest request = _addRoleRequestFixture.Create("SuperAdmin", permissions); // Act AddRoleCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/DeleteRoleRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/DeleteRoleRequestMappingTests.cs index 1dabe506..43e92dfc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/DeleteRoleRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/DeleteRoleRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System; using System.Diagnostics.CodeAnalysis; @@ -14,12 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class DeleteRoleRequestMappingTests { + private readonly DeleteRoleRequestFixture _deleteRoleRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid roleId = Guid.NewGuid(); - DeleteRoleRequest request = new(roleId); + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(roleId); // Act DeleteRoleCommand result = request.ToCommand(); @@ -37,7 +40,7 @@ public class DeleteRoleRequestMappingTests { // Arrange Guid roleId = Guid.Parse(roleIdString); - DeleteRoleRequest request = new(roleId); + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(roleId); // Act DeleteRoleCommand result = request.ToCommand(); @@ -51,7 +54,7 @@ public class DeleteRoleRequestMappingTests public void ToCommand_WhenRoleIdIsNull_ShouldThrowInvalidOperationException() { // Arrange - DeleteRoleRequest request = new(null); + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(includeRoleId: false); // Act & Assert Assert.Throws(() => request.ToCommand()); @@ -61,7 +64,7 @@ public class DeleteRoleRequestMappingTests public void ToCommand_WhenMappingEmptyGuid_ShouldMapCorrectly() { // Arrange - DeleteRoleRequest request = new(Guid.Empty); + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(Guid.Empty); // Act DeleteRoleCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetAuthorizationRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetAuthorizationRequestMappingTests.cs index a2b4c69c..adb4ad07 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetAuthorizationRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetAuthorizationRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System; using System.Diagnostics.CodeAnalysis; @@ -14,12 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class GetAuthorizationRequestMappingTests { + private readonly GetAuthorizationRequestFixture _getAuthorizationRequestFixture = new(); + [Fact] public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid userId = Guid.NewGuid(); - GetAuthorizationRequest request = new(userId); + GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId); // Act GetAuthorizationQuery result = request.ToQuery(); @@ -33,7 +36,7 @@ public class GetAuthorizationRequestMappingTests public void ToQuery_WhenUserIdIsNull_ShouldMapCorrectly() { // Arrange - GetAuthorizationRequest request = new(null); + GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(includeUserId: false); // Act GetAuthorizationQuery result = request.ToQuery(); @@ -51,7 +54,7 @@ public class GetAuthorizationRequestMappingTests { // Arrange Guid userId = Guid.Parse(userIdString); - GetAuthorizationRequest request = new(userId); + GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId); // Act GetAuthorizationQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetRolePermissionsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetRolePermissionsRequestMappingTests.cs index aa5e15d1..ec2f2bf0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetRolePermissionsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetRolePermissionsRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System; using System.Diagnostics.CodeAnalysis; @@ -14,12 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class GetRolePermissionsRequestMappingTests { + private readonly GetRolePermissionsRequestFixture _getRolePermissionsRequestFixture = new(); + [Fact] public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid roleId = Guid.NewGuid(); - GetRolePermissionsRequest request = new(roleId); + GetRolePermissionsRequest request = _getRolePermissionsRequestFixture.Create(roleId); // Act GetRolePermissionsQuery result = request.ToQuery(); @@ -37,7 +40,7 @@ public class GetRolePermissionsRequestMappingTests { // Arrange Guid roleId = Guid.Parse(roleIdString); - GetRolePermissionsRequest request = new(roleId); + GetRolePermissionsRequest request = _getRolePermissionsRequestFixture.Create(roleId); // Act GetRolePermissionsQuery result = request.ToQuery(); @@ -51,7 +54,7 @@ public class GetRolePermissionsRequestMappingTests public void ToQuery_WhenMappingEmptyGuid_ShouldMapCorrectly() { // Arrange - GetRolePermissionsRequest request = new(Guid.Empty); + GetRolePermissionsRequest request = _getRolePermissionsRequestFixture.Create(Guid.Empty); // Act GetRolePermissionsQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetUserPermissionsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetUserPermissionsRequestMappingTests.cs index 40e79754..7c4756f6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetUserPermissionsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetUserPermissionsRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System; using System.Diagnostics.CodeAnalysis; @@ -14,12 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class GetUserPermissionsRequestMappingTests { + private readonly GetUserPermissionsRequestFixture _getUserPermissionsRequestFixture = new(); + [Fact] public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid userId = Guid.NewGuid(); - GetUserPermissionsRequest request = new(userId); + GetUserPermissionsRequest request = _getUserPermissionsRequestFixture.Create(userId); // Act GetUserPermissionsQuery result = request.ToQuery(); @@ -33,7 +36,7 @@ public class GetUserPermissionsRequestMappingTests public void ToQuery_WhenUserIdIsNull_ShouldMapCorrectly() { // Arrange - GetUserPermissionsRequest request = new(null); + GetUserPermissionsRequest request = _getUserPermissionsRequestFixture.Create(includeUserId: false); // Act GetUserPermissionsQuery result = request.ToQuery(); @@ -51,7 +54,7 @@ public class GetUserPermissionsRequestMappingTests { // Arrange Guid userId = Guid.Parse(userIdString); - GetUserPermissionsRequest request = new(userId); + GetUserPermissionsRequest request = _getUserPermissionsRequestFixture.Create(userId); // Act GetUserPermissionsQuery result = request.ToQuery(); @@ -65,7 +68,7 @@ public class GetUserPermissionsRequestMappingTests public void ToQuery_WhenMappingEmptyGuid_ShouldMapCorrectly() { // Arrange - GetUserPermissionsRequest request = new(Guid.Empty); + GetUserPermissionsRequest request = _getUserPermissionsRequestFixture.Create(Guid.Empty); // Act GetUserPermissionsQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetUserRoleRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetUserRoleRequestMappingTests.cs index 0b6fd4b2..37c39cd9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetUserRoleRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/GetUserRoleRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System; using System.Diagnostics.CodeAnalysis; @@ -14,12 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class GetUserRoleRequestMappingTests { + private readonly GetUserRoleRequestFixture _getUserRoleRequestFixture = new(); + [Fact] public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid userId = Guid.NewGuid(); - GetUserRoleRequest request = new(userId); + GetUserRoleRequest request = _getUserRoleRequestFixture.Create(userId); // Act GetUserRoleQuery result = request.ToQuery(); @@ -33,7 +36,7 @@ public class GetUserRoleRequestMappingTests public void ToQuery_WhenUserIdIsNull_ShouldMapCorrectly() { // Arrange - GetUserRoleRequest request = new(null); + GetUserRoleRequest request = _getUserRoleRequestFixture.Create(includeUserId: false); // Act GetUserRoleQuery result = request.ToQuery(); @@ -51,7 +54,7 @@ public class GetUserRoleRequestMappingTests { // Arrange Guid userId = Guid.Parse(userIdString); - GetUserRoleRequest request = new(userId); + GetUserRoleRequest request = _getUserRoleRequestFixture.Create(userId); // Act GetUserRoleQuery result = request.ToQuery(); @@ -65,7 +68,7 @@ public class GetUserRoleRequestMappingTests public void ToQuery_WhenMappingEmptyGuid_ShouldMapCorrectly() { // Arrange - GetUserRoleRequest request = new(Guid.Empty); + GetUserRoleRequest request = _getUserRoleRequestFixture.Create(Guid.Empty); // Act GetUserRoleQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UpdateRoleRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UpdateRoleRequestMappingTests.cs index 8d72b692..583ce3ca 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UpdateRoleRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UpdateRoleRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System; using System.Collections.Generic; @@ -15,12 +16,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class UpdateRoleRequestMappingTests { + private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange List permissions = [Guid.NewGuid(), Guid.NewGuid()]; - UpdateRoleRequest request = new( + UpdateRoleRequest request = _updateRoleRequestFixture.Create( Guid.NewGuid(), "Admin", permissions @@ -43,7 +46,7 @@ public class UpdateRoleRequestMappingTests public void ToCommand_WhenMappingDifferentRoleNames_ShouldMapCorrectly(string roleName) { // Arrange - UpdateRoleRequest request = new( + UpdateRoleRequest request = _updateRoleRequestFixture.Create( Guid.NewGuid(), roleName, [Guid.NewGuid()] @@ -64,7 +67,7 @@ public class UpdateRoleRequestMappingTests public void ToCommand_WhenMappingDifferentRoleIds_ShouldMapCorrectly(string roleIdString) { // Arrange - UpdateRoleRequest request = new( + UpdateRoleRequest request = _updateRoleRequestFixture.Create( Guid.Parse(roleIdString), "Admin", [Guid.NewGuid()] @@ -88,7 +91,7 @@ public class UpdateRoleRequestMappingTests Guid.Parse("00000000-0000-0000-0000-000000000002"), Guid.Parse("00000000-0000-0000-0000-000000000003") ]; - UpdateRoleRequest request = new(Guid.NewGuid(), "Admin", permissions); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(Guid.NewGuid(), "Admin", permissions); // Act UpdateRoleCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UpdateUserRoleAndPermissionsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UpdateUserRoleAndPermissionsRequestMappingTests.cs index d34d238c..bc7d27a1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UpdateUserRoleAndPermissionsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UpdateUserRoleAndPermissionsRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authorization; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System; using System.Collections.Generic; @@ -15,12 +16,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class UpdateUserRoleAndPermissionsRequestMappingTests { + private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange List permissions = [Guid.NewGuid()]; - UpdateUserRoleAndPermissionsRequest request = new( + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create( Guid.NewGuid(), Guid.NewGuid(), permissions @@ -41,10 +44,11 @@ public class UpdateUserRoleAndPermissionsRequestMappingTests { // Arrange List permissions = [Guid.NewGuid()]; - UpdateUserRoleAndPermissionsRequest request = new( + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create( Guid.NewGuid(), - null, - permissions + roleId: null, + permissions: permissions, + includeRoleId: false ); // Act @@ -64,7 +68,7 @@ public class UpdateUserRoleAndPermissionsRequestMappingTests public void ToCommand_WhenMappingDifferentUserIds_ShouldMapCorrectly(string userIdString) { // Arrange - UpdateUserRoleAndPermissionsRequest request = new( + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create( Guid.Parse(userIdString), Guid.NewGuid(), [Guid.NewGuid()] @@ -88,7 +92,7 @@ public class UpdateUserRoleAndPermissionsRequestMappingTests Guid.Parse("00000000-0000-0000-0000-000000000002"), Guid.Parse("00000000-0000-0000-0000-000000000003") ]; - UpdateUserRoleAndPermissionsRequest request = new( + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create( Guid.NewGuid(), Guid.NewGuid(), permissions diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs index 1501d085..5a491da7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs @@ -20,13 +20,13 @@ public class GenreDtoMappingTests private readonly GenreDtoFixture _genreDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingValidGenreDto_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidGenreDto_ShouldMapCorrectly() { // Arrange GenreDto genreDto = _genreDtoFixture.Create(name: "Rock"); // Act - Result result = genreDto.ToDomainEntity(); + Result result = genreDto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -39,13 +39,13 @@ public class GenreDtoMappingTests [InlineData("Jazz")] [InlineData("Classical")] [InlineData("Pop")] - public void ToDomainEntity_WhenMappingDifferentValidGenreDtos_ShouldMapCorrectly(string name) + public void ToDomainValueObject_WhenMappingDifferentValidGenreDtos_ShouldMapCorrectly(string name) { // Arrange GenreDto genreDto = _genreDtoFixture.Create(name: name); // Act - Result result = genreDto.ToDomainEntity(); + Result result = genreDto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -57,13 +57,13 @@ public class GenreDtoMappingTests [InlineData("")] [InlineData(" ")] [InlineData(null)] - public void ToDomainEntity_WhenMappingInvalidGenreDto_ShouldReturnError(string? invalidName) + public void ToDomainValueObject_WhenMappingInvalidGenreDto_ShouldReturnError(string? invalidName) { // Arrange GenreDto genreDto = _genreDtoFixture.Create(name: invalidName, includeName: invalidName is not null); // Act - Result result = genreDto.ToDomainEntity(); + Result result = genreDto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -82,7 +82,7 @@ public class GenreDtoMappingTests ]; // Act - IEnumerable> results = genreDtos.ToDomainEntities(); + IEnumerable> results = genreDtos.ToDomainValueObjects(); // Assert Assert.NotNull(results); @@ -109,7 +109,7 @@ public class GenreDtoMappingTests ]; // Act - IEnumerable> results = genreDtos.ToDomainEntities(); + IEnumerable> results = genreDtos.ToDomainValueObjects(); // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs index 898bd666..f883cb42 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs @@ -70,13 +70,13 @@ public class GenreEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingValidGenreEntity_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidGenreEntity_ShouldMapCorrectly() { // Arrange GenreEntity entity = _genreEntityFixture.Create(name: "Fiction"); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -88,13 +88,13 @@ public class GenreEntityMappingTests [InlineData("")] [InlineData(" ")] [InlineData(null)] - public void ToDomainEntity_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName) + public void ToDomainValueObject_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName) { // Arrange GenreEntity entity = _genreEntityFixture.Create(name: invalidName, includeName: invalidName is not null); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -102,7 +102,7 @@ public class GenreEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidGenreEntities_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidGenreEntities_ShouldMapAllCorrectly() { // Arrange List entities = @@ -114,7 +114,7 @@ public class GenreEntityMappingTests ]; // Act - IEnumerable> results = entities.ToDomainEntities(); + IEnumerable> results = entities.ToDomainValueObjects(); // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/LanguageInfoDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/LanguageInfoDtoMappingTests.cs index f73d1053..59772705 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/LanguageInfoDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/LanguageInfoDtoMappingTests.cs @@ -18,13 +18,13 @@ public class LanguageInfoDtoMappingTests private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingCompleteLanguageInfoDto_ShouldMapAllPropertiesCorrectly() + public void ToDomainValueObject_WhenMappingCompleteLanguageInfoDto_ShouldMapAllPropertiesCorrectly() { // Arrange LanguageInfoDto dto = _languageInfoDtoFixture.Create(languageCode: "EN", languageName: "English", nativeName: "English"); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -35,13 +35,13 @@ public class LanguageInfoDtoMappingTests } [Fact] - public void ToDomainEntity_WhenNativeNameIsMissing_ShouldMapWithoutNativeName() + public void ToDomainValueObject_WhenNativeNameIsMissing_ShouldMapWithoutNativeName() { // Arrange LanguageInfoDto dto = _languageInfoDtoFixture.Create(includeNativeName: false); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/ReleaseInfoDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/ReleaseInfoDtoMappingTests.cs index 8d613e8a..87a0230b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/ReleaseInfoDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/ReleaseInfoDtoMappingTests.cs @@ -20,7 +20,7 @@ public class ReleaseInfoDtoMappingTests private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingCompleteReleaseInfoDto_ShouldMapAllPropertiesCorrectly() + public void ToDomainValueObject_WhenMappingCompleteReleaseInfoDto_ShouldMapAllPropertiesCorrectly() { // Arrange ReleaseInfoDto dto = _releaseInfoDtoFixture.Create( @@ -32,7 +32,7 @@ public class ReleaseInfoDtoMappingTests releaseVersion: "Director's Cut"); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -51,13 +51,13 @@ public class ReleaseInfoDtoMappingTests } [Fact] - public void ToDomainEntity_WhenOptionalValuesAreMissing_ShouldMapWithoutOptionalValues() + public void ToDomainValueObject_WhenOptionalValuesAreMissing_ShouldMapWithoutOptionalValues() { // Arrange ReleaseInfoDto dto = _releaseInfoDtoFixture.Create(); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -70,7 +70,7 @@ public class ReleaseInfoDtoMappingTests } [Fact] - public void ToDomainEntity_WhenOriginalReleaseDateAndYearDoNotMatch_ShouldReturnError() + public void ToDomainValueObject_WhenOriginalReleaseDateAndYearDoNotMatch_ShouldReturnError() { // Arrange ReleaseInfoDto dto = _releaseInfoDtoFixture.Create( @@ -78,14 +78,14 @@ public class ReleaseInfoDtoMappingTests originalReleaseYear: 2024); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); } [Fact] - public void ToDomainEntity_WhenReReleaseDateAndYearDoNotMatch_ShouldReturnError() + public void ToDomainValueObject_WhenReReleaseDateAndYearDoNotMatch_ShouldReturnError() { // Arrange ReleaseInfoDto dto = _releaseInfoDtoFixture.Create( @@ -93,7 +93,7 @@ public class ReleaseInfoDtoMappingTests reReleaseYear: 2024); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs index 22ca3c9c..0820d7ff 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs @@ -20,13 +20,13 @@ public class TagDtoMappingTests private readonly TagDtoFixture _tagDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingValidTagDto_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidTagDto_ShouldMapCorrectly() { // Arrange TagDto tagDto = _tagDtoFixture.Create(name: "indie"); // Act - Result result = tagDto.ToDomainEntity(); + Result result = tagDto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -40,13 +40,13 @@ public class TagDtoMappingTests [InlineData("instrumental")] [InlineData("live")] [InlineData("acoustic")] - public void ToDomainEntity_WhenMappingDifferentValidTagDtos_ShouldMapCorrectly(string name) + public void ToDomainValueObject_WhenMappingDifferentValidTagDtos_ShouldMapCorrectly(string name) { // Arrange TagDto tagDto = _tagDtoFixture.Create(name: name); // Act - Result result = tagDto.ToDomainEntity(); + Result result = tagDto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -58,13 +58,13 @@ public class TagDtoMappingTests [InlineData("")] [InlineData(" ")] [InlineData(null)] - public void ToDomainEntity_WhenMappingInvalidTagDto_ShouldReturnError(string? invalidName) + public void ToDomainValueObject_WhenMappingInvalidTagDto_ShouldReturnError(string? invalidName) { // Arrange TagDto tagDto = _tagDtoFixture.Create(name: invalidName, includeName: invalidName is not null); // Act - Result result = tagDto.ToDomainEntity(); + Result result = tagDto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -83,7 +83,7 @@ public class TagDtoMappingTests ]; // Act - IEnumerable> results = tagDtos.ToDomainEntities(); + IEnumerable> results = tagDtos.ToDomainValueObjects(); // Assert Assert.NotNull(results); @@ -110,7 +110,7 @@ public class TagDtoMappingTests ]; // Act - IEnumerable> results = tagDtos.ToDomainEntities(); + IEnumerable> results = tagDtos.ToDomainValueObjects(); // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs index 49ff084f..5041647d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs @@ -70,13 +70,13 @@ public class TagEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingValidTagEntity_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidTagEntity_ShouldMapCorrectly() { // Arrange TagEntity entity = _tagEntityFixture.Create(name: "Fantasy"); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -88,13 +88,13 @@ public class TagEntityMappingTests [InlineData("")] [InlineData(" ")] [InlineData(null)] - public void ToDomainEntity_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName) + public void ToDomainValueObject_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName) { // Arrange TagEntity entity = _tagEntityFixture.Create(name: invalidName, includeName: invalidName is not null); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -102,7 +102,7 @@ public class TagEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidTagEntities_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidTagEntities_ShouldMapAllCorrectly() { // Arrange List entities = @@ -114,7 +114,7 @@ public class TagEntityMappingTests ]; // Act - IEnumerable> results = entities.ToDomainEntities(); + IEnumerable> results = entities.ToDomainValueObjects(); // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs index 0cc417ea..729367d1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs @@ -40,7 +40,7 @@ public class CheckPathExistsRequestMappingTests public void ToQuery_WhenMappingWithDifferentPathsAndHiddenElementsFlag_ShouldMapCorrectly(string path, bool shouldIncludeHiddenElements) { // Arrange - CheckPathExistsRequest request = new(path, shouldIncludeHiddenElements); + CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path, shouldIncludeHiddenElements); // Act CheckPathExistsQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs index 7f8331db..a471e395 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs @@ -40,7 +40,7 @@ public class CombinePathRequestMappingTests public void ToCommand_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string originalPath, string newPath) { // Arrange - CombinePathRequest request = new(originalPath, newPath); + CombinePathRequest request = _combinePathRequestFixture.Create(originalPath, newPath); // Act CombinePathCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs index 2ff9cf64..092e0b06 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs @@ -39,7 +39,7 @@ public class GetPathParentRequestMappingTests public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path) { // Arrange - GetPathParentRequest request = new(path); + GetPathParentRequest request = _getPathParentRequestFixture.Create(path); // Act GetPathParentQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs index c771675e..07b51e01 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs @@ -40,7 +40,7 @@ public class GetPathRootRequestMappingTests public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path) { // Arrange - GetPathRootRequest request = new(path); + GetPathRootRequest request = _getPathRootRequestFixture.Create(path); // Act GetPathRootQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs index 64572d14..be272e0d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs @@ -40,7 +40,7 @@ public class SplitPathRequestMappingTests public void ToCommand_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path) { // Arrange - SplitPathRequest request = new(path); + SplitPathRequest request = _splitPathRequestFixture.Create(path); // Act SplitPathCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs index d55ea39d..e8db906b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs @@ -42,7 +42,7 @@ public class ValidatePathRequestMappingTests public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path) { // Arrange - ValidatePathRequest request = new(path); + ValidatePathRequest request = _validatePathRequestFixture.Create(path); // Act ValidatePathQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs index 119e6166..e2667283 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs @@ -40,7 +40,7 @@ public class GetThumbnailRequestMappingTests public void ToQuery_WhenMappingWithDifferentPathsAndQualities_ShouldMapCorrectly(string path, int quality) { // Arrange - GetThumbnailRequest request = new(path, quality); + GetThumbnailRequest request = _getThumbnailRequestFixture.Create(path, quality); // Act GetThumbnailQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs index 26c977a6..3deb893b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs @@ -53,7 +53,7 @@ public class ThumbnailMappingTests { // Arrange byte[] bytes = [.. _fixture.CreateMany(100)]; - Thumbnail domainModel = new(imageType, bytes); + Thumbnail domainModel = _thumbnailFixture.Create(imageType, bytes); // Act ThumbnailResponse result = domainModel.ToResponse(); @@ -70,7 +70,7 @@ public class ThumbnailMappingTests // Arrange ImageType imageType = _fixture.Create(); byte[] emptyBytes = []; - Thumbnail domainModel = new(imageType, emptyBytes); + Thumbnail domainModel = _thumbnailFixture.Create(imageType, emptyBytes); // Act ThumbnailResponse result = domainModel.ToResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMappingTests.cs index f327f806..7cd01c8d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMappingTests.cs @@ -26,7 +26,7 @@ public class AddAlbumCommandMappingTests { private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); @@ -46,7 +46,7 @@ public class AddAlbumCommandMappingTests Assert.Equal(command.Metadata!.Title, album.Metadata.Title); Assert.Equal(command.MediaFormat, album.MediaFormat.Value); Assert.Equal(command.Barcode, album.Barcode.Value.Value); - Assert.Equal(command.CatalogNumber, album.CatalogNumber.Value); + Assert.Equal(command.CatalogNumbers, album.CatalogNumbers); Assert.Equal(command.MusicBrainzReleaseId, album.MusicBrainzReleaseId.Value.Value); Assert.Equal(command.MusicBrainzReleaseGroupId, album.MusicBrainzReleaseGroupId.Value.Value); Assert.Equal(command.MusicBrainzReleaseArtistId, album.MusicBrainzReleaseArtistId.Value.Value); @@ -95,7 +95,7 @@ public class AddAlbumCommandMappingTests AddAlbumCommand command = _addAlbumCommandFixture.Create( includeMediaFormat: false, includeBarcode: false, - includeCatalogNumber: false, + includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false, @@ -112,7 +112,7 @@ public class AddAlbumCommandMappingTests Assert.Equal(command.Metadata!.Title, album.Metadata.Title); Assert.False(album.MediaFormat.HasValue); Assert.False(album.Barcode.HasValue); - Assert.False(album.CatalogNumber.HasValue); + Assert.Empty(album.CatalogNumbers); Assert.False(album.MusicBrainzReleaseId.HasValue); Assert.False(album.MusicBrainzReleaseGroupId.HasValue); Assert.False(album.MusicBrainzReleaseArtistId.HasValue); @@ -123,7 +123,7 @@ public class AddAlbumCommandMappingTests { // Arrange AddAlbumCommand command = _addAlbumCommandFixture.Create( - metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act Result result = command.ToDomainEntity(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMappingTests.cs index 8a38f7b6..e13dabac 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMappingTests.cs @@ -38,7 +38,7 @@ public class AddAlbumRequestMappingTests Assert.Equal(request.Metadata, result.Metadata); Assert.Equal(request.MediaFormat, result.MediaFormat); Assert.Equal(request.Barcode, result.Barcode); - Assert.Equal(request.CatalogNumber, result.CatalogNumber); + Assert.Equal(request.CatalogNumbers, result.CatalogNumbers); Assert.Equal(request.MusicBrainzReleaseId, result.MusicBrainzReleaseId); Assert.Equal(request.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId); Assert.Equal(request.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId); @@ -80,7 +80,7 @@ public class AddAlbumRequestMappingTests AddAlbumRequest request = _addAlbumRequestFixture.Create( includeMediaFormat: false, includeBarcode: false, - includeCatalogNumber: false, + includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false, @@ -93,7 +93,7 @@ public class AddAlbumRequestMappingTests Assert.NotNull(result.Metadata); Assert.Null(result.MediaFormat); Assert.Null(result.Barcode); - Assert.Null(result.CatalogNumber); + Assert.Null(result.CatalogNumbers); Assert.Null(result.MusicBrainzReleaseId); Assert.Null(result.MusicBrainzReleaseGroupId); Assert.Null(result.MusicBrainzReleaseArtistId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs index d2d2676a..7da1e576 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs @@ -6,6 +6,8 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -29,6 +31,9 @@ public class AlbumEntityMappingTests private readonly GenreEntityFixture _genreEntityFixture = new(); private readonly TagEntityFixture _tagEntityFixture = new(); private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); [Fact] public void ToDomainEntity_WhenMappingValidAlbumEntity_ShouldMapAllPropertiesCorrectly() @@ -64,13 +69,13 @@ public class AlbumEntityMappingTests Assert.Equal(entity.OriginalLanguageCode!.ToLowerInvariant(), album.Metadata.OriginalLanguage.Value.LanguageCode); Assert.Equal(entity.OriginalLanguageName, album.Metadata.OriginalLanguage.Value.LanguageName); Assert.Equal(entity.OriginalLanguageNativeName, album.Metadata.OriginalLanguage.Value.NativeName.Value); - Assert.Equal(entity.ReleaseType, album.Metadata.ReleaseType.Value); + Assert.Equal(entity.ReleaseTypes.Select(releaseType => releaseType.ReleaseType), album.Metadata.ReleaseTypes); Assert.Equal(entity.ReleaseStatus, album.Metadata.ReleaseStatus.Value); Assert.Equal(entity.TotalDiscs, album.Metadata.TotalDiscs.Value); Assert.Equal(entity.TotalTracks, album.Metadata.TotalTracks); Assert.Equal(entity.MediaFormat, album.MediaFormat.Value); Assert.Equal(entity.Barcode, album.Barcode.Value.Value); - Assert.Equal(entity.CatalogNumber, album.CatalogNumber.Value); + Assert.Equal(entity.CatalogNumbers.Select(catalogNumber => catalogNumber.CatalogNumber), album.CatalogNumbers); Assert.Equal(entity.MusicBrainzReleaseId, album.MusicBrainzReleaseId.Value.Value); Assert.Equal(entity.MusicBrainzReleaseGroupId, album.MusicBrainzReleaseGroupId.Value.Value); Assert.Equal(entity.MusicBrainzReleaseArtistId, album.MusicBrainzReleaseArtistId.Value.Value); @@ -102,7 +107,7 @@ public class AlbumEntityMappingTests includeReleaseStatus: false, includeTotalDiscs: false, includeMediaFormat: false, - includeCatalogNumber: false, + includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); @@ -123,12 +128,12 @@ public class AlbumEntityMappingTests Assert.Empty(album.Metadata.Tags); Assert.False(album.Metadata.Language.HasValue); Assert.False(album.Metadata.OriginalLanguage.HasValue); - Assert.False(album.Metadata.ReleaseType.HasValue); + Assert.Empty(album.Metadata.ReleaseTypes); Assert.False(album.Metadata.ReleaseStatus.HasValue); Assert.False(album.Metadata.TotalDiscs.HasValue); Assert.False(album.MediaFormat.HasValue); Assert.False(album.Barcode.HasValue); - Assert.False(album.CatalogNumber.HasValue); + Assert.Empty(album.CatalogNumbers); Assert.False(album.MusicBrainzReleaseId.HasValue); Assert.False(album.MusicBrainzReleaseGroupId.HasValue); Assert.False(album.MusicBrainzReleaseArtistId.HasValue); @@ -231,7 +236,7 @@ public class AlbumEntityMappingTests { // Arrange TrackEntity trackEntity = _trackEntityFixture.Create(); - trackEntity.Isrcs = [new TrackIsrcEntity("not-an-isrc")]; + trackEntity.Isrcs = [_trackIsrcEntityFixture.Create(value: "not-an-isrc")]; AlbumEntity entity = _albumEntityFixture.Create(tracks: [trackEntity]); // Act @@ -275,20 +280,20 @@ public class AlbumEntityMappingTests Assert.Equal(entity.OriginalLanguageNativeName, result.Metadata.OriginalLanguage.NativeName); Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), result.Metadata.Tags!.Select(tag => tag.Name).OrderBy(name => name)); Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), result.Metadata.Genres!.Select(genre => genre.Name).OrderBy(name => name)); - Assert.Equal(entity.ReleaseType, result.Metadata.ReleaseType); + Assert.Equal(entity.ReleaseTypes.Select(releaseType => releaseType.ReleaseType), result.Metadata.ReleaseTypes); Assert.Equal(entity.ReleaseStatus, result.Metadata.ReleaseStatus); Assert.Equal(entity.TotalDiscs, result.Metadata.TotalDiscs); Assert.Equal(entity.TotalTracks, result.Metadata.TotalTracks); Assert.Equal(entity.MediaFormat, result.MediaFormat); Assert.Equal(entity.Barcode, result.Barcode); - Assert.Equal(entity.CatalogNumber, result.CatalogNumber); + Assert.Equal(entity.CatalogNumbers.Select(catalogNumber => catalogNumber.CatalogNumber), result.CatalogNumbers); Assert.Equal(entity.MusicBrainzReleaseId, result.MusicBrainzReleaseId); Assert.Equal(entity.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId); Assert.Equal(entity.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId); Assert.Equal(entity.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(entity.UpdatedOnUtc, result.UpdatedOnUtc); - Assert.Equal(entity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role)), result.Contributors); - Assert.Equal(entity.Ratings.Select(rating => new AudioRatingDto(rating.Value, rating.MaxValue, rating.Source, rating.VoteCount)), result.Ratings); + Assert.Equal(entity.Contributors.Select(contributor => _mediaContributorReferenceDtoFixture.Create(contributorId: contributor.MediaContributorId, role: contributor.Role)), result.Contributors); + Assert.Equal(entity.Ratings.Select(rating => _audioRatingDtoFixture.Create(value: rating.Value, maxValue: rating.MaxValue, source: rating.Source, voteCount: rating.VoteCount)), result.Ratings); Assert.Equal(entity.Tracks.Select(track => track.Id), result.Tracks!.Select(track => track.Id)); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMappingTests.cs index 89be22a7..c9a37ed3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMappingTests.cs @@ -58,13 +58,13 @@ public class AlbumMappingTests Assert.Equal(album.Metadata.OriginalLanguage.HasValue && album.Metadata.OriginalLanguage.Value.NativeName.HasValue ? album.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName); Assert.Equal(album.Metadata.Genres.ToRepositoryEntities().Distinct().Select(genre => genre.Name).OrderBy(name => name), result.Genres.Select(genre => genre.Name).OrderBy(name => name)); Assert.Equal(album.Metadata.Tags.ToRepositoryEntities().Distinct().Select(tag => tag.Name).OrderBy(name => name), result.Tags.Select(tag => tag.Name).OrderBy(name => name)); - Assert.Equal(album.Metadata.ReleaseType.HasValue ? album.Metadata.ReleaseType.Value : null, result.ReleaseType); + Assert.Equal(album.Metadata.ReleaseTypes.OrderBy(releaseType => releaseType), result.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).OrderBy(releaseType => releaseType)); Assert.Equal(album.Metadata.ReleaseStatus.HasValue ? album.Metadata.ReleaseStatus.Value : null, result.ReleaseStatus); Assert.Equal(album.Metadata.TotalDiscs.HasValue ? album.Metadata.TotalDiscs.Value : null, result.TotalDiscs); Assert.Equal(album.Metadata.TotalTracks, result.TotalTracks); Assert.Equal(album.MediaFormat.HasValue ? album.MediaFormat.Value : null, result.MediaFormat); Assert.Equal(album.Barcode.HasValue ? album.Barcode.Value.Value : null, result.Barcode); - Assert.Equal(album.CatalogNumber.HasValue ? album.CatalogNumber.Value : null, result.CatalogNumber); + Assert.Equal(album.CatalogNumbers, result.CatalogNumbers.Select(catalogNumber => catalogNumber.CatalogNumber)); Assert.Equal(album.MusicBrainzReleaseId.HasValue ? album.MusicBrainzReleaseId.Value.Value : null, result.MusicBrainzReleaseId); Assert.Equal(album.MusicBrainzReleaseGroupId.HasValue ? album.MusicBrainzReleaseGroupId.Value.Value : null, result.MusicBrainzReleaseGroupId); Assert.Equal(album.MusicBrainzReleaseArtistId.HasValue ? album.MusicBrainzReleaseArtistId.Value.Value : null, result.MusicBrainzReleaseArtistId); @@ -133,7 +133,7 @@ public class AlbumMappingTests Album album = _albumFixture.Create( mediaFormat: Optional.None(), barcode: Optional.None(), - catalogNumber: Optional.None(), + catalogNumbers: [], musicBrainzReleaseId: Optional.None(), musicBrainzReleaseGroupId: Optional.None(), musicBrainzReleaseArtistId: Optional.None(), @@ -147,7 +147,7 @@ public class AlbumMappingTests // Assert Assert.Null(result.MediaFormat); Assert.Null(result.Barcode); - Assert.Null(result.CatalogNumber); + Assert.Empty(result.CatalogNumbers); Assert.Null(result.MusicBrainzReleaseId); Assert.Null(result.MusicBrainzReleaseGroupId); Assert.Null(result.MusicBrainzReleaseArtistId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMappingTests.cs index a7a609a2..91d13d31 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMappingTests.cs @@ -1,13 +1,20 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion @@ -22,129 +29,119 @@ public class AlbumMetadataDtoMappingTests { private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); - private readonly TagDtoFixture _tagDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); - private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() + public void ApplyTo_WhenMappingCompleteDto_ShouldApplyAllPropertiesCorrectly() { // Arrange + (Artist artist, Album album) = CreateDomainArtist(); AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(); + List contributors = _musicMediaContributorFixture.CreateMany(2); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, album, contributors); // Assert Assert.False(result.IsFailure); - AlbumMetadata metadata = result.Value; - Assert.Equal(dto.Title, metadata.Title); - Assert.True(metadata.OriginalTitle.HasValue); - Assert.Equal(dto.OriginalTitle, metadata.OriginalTitle.Value); - Assert.True(metadata.Description.HasValue); - Assert.Equal(dto.Description, metadata.Description.Value); - Assert.True(metadata.ReleaseInfo.OriginalReleaseDate.HasValue); - Assert.Equal(dto.ReleaseInfo!.OriginalReleaseDate, metadata.ReleaseInfo.OriginalReleaseDate.Value); - Assert.True(metadata.ReleaseInfo.OriginalReleaseYear.HasValue); - Assert.Equal(dto.ReleaseInfo.OriginalReleaseYear, metadata.ReleaseInfo.OriginalReleaseYear.Value); - Assert.True(metadata.ReleaseInfo.ReReleaseDate.HasValue); - Assert.Equal(dto.ReleaseInfo.ReReleaseDate, metadata.ReleaseInfo.ReReleaseDate.Value); - Assert.True(metadata.ReleaseInfo.ReReleaseYear.HasValue); - Assert.Equal(dto.ReleaseInfo.ReReleaseYear, metadata.ReleaseInfo.ReReleaseYear.Value); - Assert.True(metadata.ReleaseInfo.ReleaseCountry.HasValue); - Assert.Equal(dto.ReleaseInfo.ReleaseCountry, metadata.ReleaseInfo.ReleaseCountry.Value); - Assert.True(metadata.ReleaseInfo.ReleaseVersion.HasValue); - Assert.Equal(dto.ReleaseInfo.ReleaseVersion, metadata.ReleaseInfo.ReleaseVersion.Value); - Assert.True(metadata.Language.HasValue); - Assert.Equal(dto.Language!.LanguageCode!.ToLowerInvariant(), metadata.Language.Value.LanguageCode); - Assert.Equal(dto.Language.LanguageName, metadata.Language.Value.LanguageName); - Assert.Equal(dto.Language.NativeName, metadata.Language.Value.NativeName.Value); - Assert.True(metadata.OriginalLanguage.HasValue); - Assert.Equal(dto.OriginalLanguage!.LanguageCode!.ToLowerInvariant(), metadata.OriginalLanguage.Value.LanguageCode); - Assert.Equal(dto.OriginalLanguage.LanguageName, metadata.OriginalLanguage.Value.LanguageName); - Assert.Equal(dto.OriginalLanguage.NativeName, metadata.OriginalLanguage.Value.NativeName.Value); - Assert.Equal(dto.Genres!.Select(genre => genre.Name), metadata.Genres.Select(genre => genre.Name)); - Assert.Equal(dto.Tags!.Select(tag => tag.Name), metadata.Tags.Select(tag => tag.Name)); - Assert.True(metadata.ReleaseType.HasValue); - Assert.Equal(dto.ReleaseType, metadata.ReleaseType.Value); - Assert.True(metadata.ReleaseStatus.HasValue); - Assert.Equal(dto.ReleaseStatus, metadata.ReleaseStatus.Value); - Assert.True(metadata.TotalDiscs.HasValue); - Assert.Equal(dto.TotalDiscs, metadata.TotalDiscs.Value); - Assert.Equal(dto.TotalTracks, metadata.TotalTracks); + Assert.Equal(dto.Title, album.Metadata.Title); + Assert.True(album.Metadata.OriginalTitle.HasValue); + Assert.Equal(dto.OriginalTitle, album.Metadata.OriginalTitle.Value); + Assert.True(album.Metadata.Description.HasValue); + Assert.Equal(dto.Description, album.Metadata.Description.Value); + Assert.Equal(dto.TotalTracks, album.Metadata.TotalTracks); + Assert.Equal(dto.ReleaseTypes!.Count, album.Metadata.ReleaseTypes.Count); + Assert.True(album.Metadata.ReleaseStatus.HasValue); + Assert.Equal(dto.ReleaseStatus, album.Metadata.ReleaseStatus.Value); + Assert.True(album.Disambiguation.HasValue); + Assert.Equal(dto.Disambiguation, album.Disambiguation.Value); + Assert.True(album.Script.HasValue); + Assert.Equal(dto.Script, album.Script.Value); + Assert.True(album.Barcode.HasValue); + Assert.Equal(dto.Barcode, album.Barcode.Value.Value); + Assert.NotEmpty(album.CatalogNumbers); + Assert.Equal(dto.CatalogNumbers, album.CatalogNumbers); + Assert.True(album.Label.HasValue); + Assert.Equal(dto.Label, album.Label.Value); + Assert.True(album.ASIN.HasValue); + Assert.Equal(dto.ASIN, album.ASIN.Value); + Assert.True(album.MusicBrainzReleaseId.HasValue); + Assert.Equal(dto.MusicBrainzReleaseId, album.MusicBrainzReleaseId.Value.Value); + Assert.True(album.MusicBrainzReleaseGroupId.HasValue); + Assert.Equal(dto.MusicBrainzReleaseGroupId, album.MusicBrainzReleaseGroupId.Value.Value); + Assert.True(album.MusicBrainzReleaseArtistId.HasValue); + Assert.Equal(dto.MusicBrainzReleaseArtistId, album.MusicBrainzReleaseArtistId.Value.Value); + Assert.Equal(contributors.Count, album.Contributors.Count); + Assert.Equal(dto.Ratings!.Count, album.Ratings.Count); } [Fact] - public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults() + public void ApplyTo_WhenBarcodeIsMissing_ShouldMapTheBarcodeToNone() { // Arrange - AlbumMetadataDto dto = _albumMetadataDtoFixture.Create( - includeOriginalTitle: false, - includeDescription: false, - includeReleaseInfo: false, - includeLanguage: false, - includeOriginalLanguage: false, - includeTags: false, - includeGenres: false, - includeReleaseType: false, - includeReleaseStatus: false, - includeTotalDiscs: false, - includeTotalTracks: false); + (Artist artist, Album album) = CreateDomainArtist(); + AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(includeBarcode: false); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, album, []); // Assert Assert.False(result.IsFailure); - AlbumMetadata metadata = result.Value; - Assert.Equal(dto.Title, metadata.Title); - Assert.False(metadata.OriginalTitle.HasValue); - Assert.False(metadata.Description.HasValue); - Assert.False(metadata.ReleaseInfo.OriginalReleaseDate.HasValue); - Assert.False(metadata.ReleaseInfo.OriginalReleaseYear.HasValue); - Assert.False(metadata.ReleaseInfo.ReReleaseDate.HasValue); - Assert.False(metadata.ReleaseInfo.ReReleaseYear.HasValue); - Assert.False(metadata.ReleaseInfo.ReleaseCountry.HasValue); - Assert.False(metadata.ReleaseInfo.ReleaseVersion.HasValue); - Assert.False(metadata.Language.HasValue); - Assert.False(metadata.OriginalLanguage.HasValue); - Assert.Empty(metadata.Genres); - Assert.Empty(metadata.Tags); - Assert.False(metadata.ReleaseType.HasValue); - Assert.False(metadata.ReleaseStatus.HasValue); - Assert.False(metadata.TotalDiscs.HasValue); - Assert.Equal(0, metadata.TotalTracks); + Assert.False(album.Barcode.HasValue); } [Fact] - public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone() + public void ApplyTo_WhenTheMetadataHasAReleaseTitle_ShouldApplyIt() { // Arrange - LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false); - AlbumMetadataDto dto = _albumMetadataDtoFixture.Create( - language: incompleteLanguage, - originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false)); + (Artist artist, Album album) = CreateDomainArtist(); + AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(releaseTitle: "Greatest Hits I"); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, album, []); // Assert Assert.False(result.IsFailure); - Assert.False(result.Value.Language.HasValue); - Assert.False(result.Value.OriginalLanguage.HasValue); + Assert.True(album.Metadata.ReleaseTitle.HasValue); + Assert.Equal("Greatest Hits I", album.Metadata.ReleaseTitle.Value); } [Fact] - public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError() + public void ApplyTo_WhenTheMetadataHasNoReleaseDate_ShouldKeepTheStoredReleaseDate() { // Arrange + (Artist artist, Album album) = CreateDomainArtist(); + DateOnly storedReleaseDate = album.Metadata.ReleaseInfo.OriginalReleaseDate.Value; + int storedReleaseYear = album.Metadata.ReleaseInfo.OriginalReleaseYear.Value; + AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(includeReleaseInfo: false); + + // Act + Result result = dto.ApplyTo(artist, album, []); + + // Assert + Assert.False(result.IsFailure); + Assert.True(album.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue); + Assert.Equal(storedReleaseDate, album.Metadata.ReleaseInfo.OriginalReleaseDate.Value); + Assert.True(album.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue); + Assert.Equal(storedReleaseYear, album.Metadata.ReleaseInfo.OriginalReleaseYear.Value); + } + + [Fact] + public void ApplyTo_WhenReleaseInfoIsInvalid_ShouldReturnError() + { + // Arrange + (Artist artist, Album album) = CreateDomainArtist(); ReleaseInfoDto releaseInfo = _releaseInfoDtoFixture.Create( originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 1999); AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(releaseInfo: releaseInfo); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, album, []); // Assert Assert.True(result.IsFailure); @@ -152,13 +149,14 @@ public class AlbumMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + public void ApplyTo_WhenGenreIsInvalid_ShouldReturnError() { // Arrange + (Artist artist, Album album) = CreateDomainArtist(); AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, album, []); // Assert Assert.True(result.IsFailure); @@ -166,16 +164,35 @@ public class AlbumMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError() + public void ApplyTo_WhenAlbumDoesNotBelongToArtist_ShouldReturnAlbumNotFound() { // Arrange - AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]); + (Artist artist, Album _) = CreateDomainArtist(); + (Artist _, Album foreignAlbum) = CreateDomainArtist(); + AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, foreignAlbum, []); // Assert Assert.True(result.IsFailure); - Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + /// + /// Creates a domain artist that owns a single album, which in turn owns a single track. + /// + /// The created domain artist, together with its album. + private (Artist artist, Album album) CreateDomainArtist() + { + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity albumEntity = _albumEntityFixture.Create( + id: albumId, + libraryId: libraryId, + tracks: [_trackEntityFixture.Create(albumId: albumId, libraryId: libraryId)]); + ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); + Artist artist = artistEntity.ToDomainEntity().Value; + return (artist, artist.Albums.First()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/MusicAlbumMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/MusicAlbumMetadataDtoMappingTests.cs new file mode 100644 index 00000000..0665256a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/MusicAlbumMetadataDtoMappingTests.cs @@ -0,0 +1,181 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicAlbumMetadataDtoMappingTests +{ + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + MusicAlbumMetadataDto dto = _musicAlbumMetadataDtoFixture.Create(); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + AlbumMetadata metadata = result.Value; + Assert.Equal(dto.Title, metadata.Title); + Assert.True(metadata.OriginalTitle.HasValue); + Assert.Equal(dto.OriginalTitle, metadata.OriginalTitle.Value); + Assert.True(metadata.Description.HasValue); + Assert.Equal(dto.Description, metadata.Description.Value); + Assert.True(metadata.ReleaseInfo.OriginalReleaseDate.HasValue); + Assert.Equal(dto.ReleaseInfo!.OriginalReleaseDate, metadata.ReleaseInfo.OriginalReleaseDate.Value); + Assert.True(metadata.ReleaseInfo.OriginalReleaseYear.HasValue); + Assert.Equal(dto.ReleaseInfo.OriginalReleaseYear, metadata.ReleaseInfo.OriginalReleaseYear.Value); + Assert.True(metadata.ReleaseInfo.ReReleaseDate.HasValue); + Assert.Equal(dto.ReleaseInfo.ReReleaseDate, metadata.ReleaseInfo.ReReleaseDate.Value); + Assert.True(metadata.ReleaseInfo.ReReleaseYear.HasValue); + Assert.Equal(dto.ReleaseInfo.ReReleaseYear, metadata.ReleaseInfo.ReReleaseYear.Value); + Assert.True(metadata.ReleaseInfo.ReleaseCountry.HasValue); + Assert.Equal(dto.ReleaseInfo.ReleaseCountry, metadata.ReleaseInfo.ReleaseCountry.Value); + Assert.True(metadata.ReleaseInfo.ReleaseVersion.HasValue); + Assert.Equal(dto.ReleaseInfo.ReleaseVersion, metadata.ReleaseInfo.ReleaseVersion.Value); + Assert.True(metadata.Language.HasValue); + Assert.Equal(dto.Language!.LanguageCode!.ToLowerInvariant(), metadata.Language.Value.LanguageCode); + Assert.Equal(dto.Language.LanguageName, metadata.Language.Value.LanguageName); + Assert.Equal(dto.Language.NativeName, metadata.Language.Value.NativeName.Value); + Assert.True(metadata.OriginalLanguage.HasValue); + Assert.Equal(dto.OriginalLanguage!.LanguageCode!.ToLowerInvariant(), metadata.OriginalLanguage.Value.LanguageCode); + Assert.Equal(dto.OriginalLanguage.LanguageName, metadata.OriginalLanguage.Value.LanguageName); + Assert.Equal(dto.OriginalLanguage.NativeName, metadata.OriginalLanguage.Value.NativeName.Value); + Assert.Equal(dto.Genres!.Select(genre => genre.Name), metadata.Genres.Select(genre => genre.Name)); + Assert.Equal(dto.Tags!.Select(tag => tag.Name), metadata.Tags.Select(tag => tag.Name)); + Assert.NotEmpty(metadata.ReleaseTypes); + Assert.Equal(dto.ReleaseTypes, metadata.ReleaseTypes); + Assert.True(metadata.ReleaseStatus.HasValue); + Assert.Equal(dto.ReleaseStatus, metadata.ReleaseStatus.Value); + Assert.True(metadata.TotalDiscs.HasValue); + Assert.Equal(dto.TotalDiscs, metadata.TotalDiscs.Value); + Assert.Equal(dto.TotalTracks, metadata.TotalTracks); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults() + { + // Arrange + MusicAlbumMetadataDto dto = _musicAlbumMetadataDtoFixture.Create( + includeOriginalTitle: false, + includeDescription: false, + includeReleaseInfo: false, + includeLanguage: false, + includeOriginalLanguage: false, + includeTags: false, + includeGenres: false, + includeReleaseTypes: false, + includeReleaseStatus: false, + includeTotalDiscs: false, + includeTotalTracks: false); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + AlbumMetadata metadata = result.Value; + Assert.Equal(dto.Title, metadata.Title); + Assert.False(metadata.OriginalTitle.HasValue); + Assert.False(metadata.Description.HasValue); + Assert.False(metadata.ReleaseInfo.OriginalReleaseDate.HasValue); + Assert.False(metadata.ReleaseInfo.OriginalReleaseYear.HasValue); + Assert.False(metadata.ReleaseInfo.ReReleaseDate.HasValue); + Assert.False(metadata.ReleaseInfo.ReReleaseYear.HasValue); + Assert.False(metadata.ReleaseInfo.ReleaseCountry.HasValue); + Assert.False(metadata.ReleaseInfo.ReleaseVersion.HasValue); + Assert.False(metadata.Language.HasValue); + Assert.False(metadata.OriginalLanguage.HasValue); + Assert.Empty(metadata.Genres); + Assert.Empty(metadata.Tags); + Assert.Empty(metadata.ReleaseTypes); + Assert.False(metadata.ReleaseStatus.HasValue); + Assert.False(metadata.TotalDiscs.HasValue); + Assert.Equal(0, metadata.TotalTracks); + } + + [Fact] + public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone() + { + // Arrange + LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false); + MusicAlbumMetadataDto dto = _musicAlbumMetadataDtoFixture.Create( + language: incompleteLanguage, + originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false)); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Language.HasValue); + Assert.False(result.Value.OriginalLanguage.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError() + { + // Arrange + ReleaseInfoDto releaseInfo = _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(2000, 1, 1), + originalReleaseYear: 1999); + MusicAlbumMetadataDto dto = _musicAlbumMetadataDtoFixture.Create(releaseInfo: releaseInfo); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + { + // Arrange + MusicAlbumMetadataDto dto = _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError() + { + // Arrange + MusicAlbumMetadataDto dto = _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMappingTests.cs index 9b067a3c..7fcf7be6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMappingTests.cs @@ -28,7 +28,7 @@ public class UpdateAlbumCommandMappingTests private readonly UpdateAlbumCommandFixture _updateAlbumCommandFixture = new(); private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); @@ -50,7 +50,7 @@ public class UpdateAlbumCommandMappingTests Assert.Equal(command.Metadata!.Title, updatedAlbum.Metadata.Title); Assert.Equal(command.MediaFormat, updatedAlbum.MediaFormat.Value); Assert.Equal(command.Barcode, updatedAlbum.Barcode.Value.Value); - Assert.Equal(command.CatalogNumber, updatedAlbum.CatalogNumber.Value); + Assert.Equal(command.CatalogNumbers, updatedAlbum.CatalogNumbers); Assert.Equal(command.MusicBrainzReleaseId, updatedAlbum.MusicBrainzReleaseId.Value.Value); Assert.Equal(command.MusicBrainzReleaseGroupId, updatedAlbum.MusicBrainzReleaseGroupId.Value.Value); Assert.Equal(command.MusicBrainzReleaseArtistId, updatedAlbum.MusicBrainzReleaseArtistId.Value.Value); @@ -70,7 +70,7 @@ public class UpdateAlbumCommandMappingTests albumId: albumId.ToString(), includeMediaFormat: false, includeBarcode: false, - includeCatalogNumber: false, + includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false, @@ -86,7 +86,7 @@ public class UpdateAlbumCommandMappingTests Assert.Equal(command.Metadata!.Title, updatedAlbum.Metadata.Title); Assert.False(updatedAlbum.MediaFormat.HasValue); Assert.False(updatedAlbum.Barcode.HasValue); - Assert.False(updatedAlbum.CatalogNumber.HasValue); + Assert.Empty(updatedAlbum.CatalogNumbers); Assert.False(updatedAlbum.MusicBrainzReleaseId.HasValue); Assert.False(updatedAlbum.MusicBrainzReleaseGroupId.HasValue); Assert.False(updatedAlbum.MusicBrainzReleaseArtistId.HasValue); @@ -104,7 +104,7 @@ public class UpdateAlbumCommandMappingTests libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), - metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act Result result = command.ToDomainEntity(artist); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMappingTests.cs index 4219f1cb..d2ac06b7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMappingTests.cs @@ -37,7 +37,7 @@ public class UpdateAlbumRequestMappingTests Assert.Equal(request.Metadata, result.Metadata); Assert.Equal(request.MediaFormat, result.MediaFormat); Assert.Equal(request.Barcode, result.Barcode); - Assert.Equal(request.CatalogNumber, result.CatalogNumber); + Assert.Equal(request.CatalogNumbers, result.CatalogNumbers); Assert.Equal(request.MusicBrainzReleaseId, result.MusicBrainzReleaseId); Assert.Equal(request.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId); Assert.Equal(request.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId); @@ -52,7 +52,7 @@ public class UpdateAlbumRequestMappingTests UpdateAlbumRequest request = _updateAlbumRequestFixture.Create( includeMediaFormat: false, includeBarcode: false, - includeCatalogNumber: false, + includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); @@ -64,7 +64,7 @@ public class UpdateAlbumRequestMappingTests Assert.NotNull(result.Metadata); Assert.Null(result.MediaFormat); Assert.Null(result.Barcode); - Assert.Null(result.CatalogNumber); + Assert.Null(result.CatalogNumbers); Assert.Null(result.MusicBrainzReleaseId); Assert.Null(result.MusicBrainzReleaseGroupId); Assert.Null(result.MusicBrainzReleaseArtistId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMappingTests.cs index 096e1e44..fe57c4d1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMappingTests.cs @@ -24,7 +24,8 @@ public class AddArtistCommandMappingTests { private readonly AddArtistCommandFixture _addArtistCommandFixture = new(); private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); [Fact] @@ -41,7 +42,7 @@ public class AddArtistCommandMappingTests Assert.False(result.IsFailure); Artist artist = result.Value; Assert.Equal(libraryId, artist.LibraryId.Value); - Assert.Equal(command.Name, artist.Name); + Assert.Equal(command.Metadata!.Name, artist.Name); Assert.True(artist.Website.HasValue); Assert.Equal(command.Website, artist.Website.Value); Assert.True(artist.MusicBrainzArtistId.HasValue); @@ -79,7 +80,7 @@ public class AddArtistCommandMappingTests // Arrange Guid libraryId = Guid.NewGuid(); AddAlbumCommand invalidAlbum = _addAlbumCommandFixture.Create( - metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); AddArtistCommand command = _addArtistCommandFixture.Create(albums: [invalidAlbum]); // Act @@ -94,7 +95,7 @@ public class AddArtistCommandMappingTests public void ToDomainEntity_WhenArtistNameIsEmpty_ShouldReturnError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(name: string.Empty); + AddArtistCommand command = _addArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: string.Empty)); // Act Result result = command.ToDomainEntity(Guid.NewGuid()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMappingTests.cs index a3d0f649..974f4d85 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMappingTests.cs @@ -32,7 +32,7 @@ public class AddArtistRequestMappingTests // Assert Assert.NotNull(result); Assert.Equal(libraryId.ToString(), result.LibraryId); - Assert.Equal(request.Name, result.Name); + Assert.Equal(request.Metadata!.Name, result.Metadata!.Name); Assert.Equal(request.Website, result.Website); Assert.Equal(request.MusicBrainzArtistId, result.MusicBrainzArtistId); Assert.Equal(request.Contributors, result.Contributors); @@ -58,7 +58,7 @@ public class AddArtistRequestMappingTests Assert.Equal(request.Albums[i].Metadata, result.Albums[i].Metadata); Assert.Equal(request.Albums[i].MediaFormat, result.Albums[i].MediaFormat); Assert.Equal(request.Albums[i].Barcode, result.Albums[i].Barcode); - Assert.Equal(request.Albums[i].CatalogNumber, result.Albums[i].CatalogNumber); + Assert.Equal(request.Albums[i].CatalogNumbers, result.Albums[i].CatalogNumbers); Assert.Equal(request.Albums[i].MusicBrainzReleaseId, result.Albums[i].MusicBrainzReleaseId); Assert.Equal(request.Albums[i].MusicBrainzReleaseGroupId, result.Albums[i].MusicBrainzReleaseGroupId); Assert.Equal(request.Albums[i].MusicBrainzReleaseArtistId, result.Albums[i].MusicBrainzReleaseArtistId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMappingTests.cs index 96fe6768..cec0e8fc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMappingTests.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.A using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Domain.Common.Errors; @@ -27,6 +28,7 @@ public class ArtistEntityMappingTests private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); [Fact] public void ToDomainEntity_WhenMappingValidArtistEntity_ShouldMapAllPropertiesCorrectly() @@ -111,10 +113,10 @@ public class ArtistEntityMappingTests Assert.NotNull(result); Assert.Equal(entity.Id, result.Id); Assert.Equal(entity.LibraryId, result.LibraryId); - Assert.Equal(entity.Name, result.Name); + Assert.Equal(entity.Name, result.Metadata.Name); Assert.Equal(entity.Website, result.Website); Assert.Equal(entity.MusicBrainzArtistId, result.MusicBrainzArtistId); - Assert.Equal(entity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role)), result.Contributors); + Assert.Equal(entity.Contributors.Select(contributor => _mediaContributorReferenceDtoFixture.Create(contributorId: contributor.MediaContributorId, role: contributor.Role)), result.Contributors); Assert.Equal(entity.Albums.Count, result.Albums!.Count); Assert.Equal(entity.Albums.Select(album => album.Id), result.Albums.Select(album => album.Id)); Assert.Equal(entity.Albums.Select(album => album.Title), result.Albums.Select(album => album.Metadata.Title)); @@ -157,7 +159,7 @@ public class ArtistEntityMappingTests for (int i = 0; i < entities.Count; i++) { Assert.Equal(entities[i].Id, results[i].Id); - Assert.Equal(entities[i].Name, results[i].Name); + Assert.Equal(entities[i].Name, results[i].Metadata.Name); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMappingTests.cs index 04bab90f..2a75cd37 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMappingTests.cs @@ -102,7 +102,7 @@ public class ArtistMappingTests Album album = _albumFixture.Create( mediaFormat: Optional.None(), barcode: Optional.None(), - catalogNumber: Optional.None(), + catalogNumbers: [], musicBrainzReleaseId: Optional.None(), musicBrainzReleaseGroupId: Optional.None(), musicBrainzReleaseArtistId: Optional.None()); @@ -122,7 +122,7 @@ public class ArtistMappingTests Assert.Single(result.Albums); Assert.Null(result.Albums[0].MediaFormat); Assert.Null(result.Albums[0].Barcode); - Assert.Null(result.Albums[0].CatalogNumber); + Assert.Empty(result.Albums[0].CatalogNumbers); Assert.Null(result.Albums[0].MusicBrainzReleaseId); Assert.Null(result.Albums[0].MusicBrainzReleaseGroupId); Assert.Null(result.Albums[0].MusicBrainzReleaseArtistId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMetadataDtoMappingTests.cs new file mode 100644 index 00000000..9f28181a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMetadataDtoMappingTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistMetadataDtoMappingTests +{ + private readonly ArtistMetadataDtoFixture _artistMetadataDtoFixture = new(); + private readonly MusicAreaDtoFixture _musicAreaDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + + [Fact] + public void ApplyTo_WhenMappingCompleteDto_ShouldApplyAllPropertiesCorrectly() + { + // Arrange + Artist artist = CreateDomainArtist(); + ArtistMetadataDto dto = _artistMetadataDtoFixture.Create(); + List contributors = _musicMediaContributorFixture.CreateMany(2); + + // Act + Result result = dto.ApplyTo(artist, contributors); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(dto.Name, artist.Name); + Assert.True(artist.SortName.HasValue); + Assert.Equal(dto.SortName, artist.SortName.Value); + Assert.True(artist.Disambiguation.HasValue); + Assert.Equal(dto.Disambiguation, artist.Disambiguation.Value); + Assert.True(artist.Country.HasValue); + Assert.Equal(dto.Country, artist.Country.Value); + Assert.True(artist.Area.HasValue); + Assert.Equal(dto.Area!.Name, artist.Area.Value.Name); + Assert.True(artist.BeginArea.HasValue); + Assert.True(artist.EndArea.HasValue); + Assert.True(artist.LifeSpanBegin.HasValue); + Assert.Equal(dto.LifeSpanBegin, artist.LifeSpanBegin.Value); + Assert.True(artist.LifeSpanEnd.HasValue); + Assert.Equal(dto.LifeSpanEnd, artist.LifeSpanEnd.Value); + Assert.Equal(dto.IsEnded, artist.IsEnded); + Assert.True(artist.Website.HasValue); + Assert.Equal(dto.Website, artist.Website.Value); + Assert.True(artist.MusicBrainzArtistId.HasValue); + Assert.Equal(dto.MusicBrainzArtistId, artist.MusicBrainzArtistId.Value.Value); + Assert.Equal(dto.Ipis!.Count, artist.Ipis.Count); + Assert.Equal(dto.Isnis!.Count, artist.Isnis.Count); + Assert.Equal(dto.Aliases!.Count, artist.Aliases.Count); + Assert.Equal(dto.Genres!.Count, artist.Genres.Count); + Assert.Equal(dto.Tags!.Count, artist.Tags.Count); + Assert.Equal(dto.Ratings!.Count, artist.Ratings.Count); + Assert.Equal(contributors.Count, artist.Contributors.Count); + } + + [Fact] + public void ApplyTo_WhenNameAndWebsiteAreMissing_ShouldPreserveTheStoredValues() + { + // Arrange + Artist artist = CreateDomainArtist(); + string storedName = artist.Name; + bool hadStoredWebsite = artist.Website.HasValue; + string? storedWebsite = artist.Website.HasValue ? artist.Website.Value : null; + ArtistMetadataDto dto = _artistMetadataDtoFixture.Create(includeName: false, includeWebsite: false); + + // Act + Result result = dto.ApplyTo(artist, []); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(storedName, artist.Name); + Assert.Equal(hadStoredWebsite, artist.Website.HasValue); + if (hadStoredWebsite) + Assert.Equal(storedWebsite, artist.Website.Value); + } + + [Fact] + public void ApplyTo_WhenAreaIsMissingItsIdentifier_ShouldMapTheAreaToNone() + { + // Arrange + Artist artist = CreateDomainArtist(); + ArtistMetadataDto dto = _artistMetadataDtoFixture.Create(area: _musicAreaDtoFixture.Create(includeMusicBrainzAreaId: false)); + + // Act + Result result = dto.ApplyTo(artist, []); + + // Assert + Assert.False(result.IsFailure); + Assert.False(artist.Area.HasValue); + } + + [Fact] + public void ApplyTo_WhenGenreIsInvalid_ShouldReturnError() + { + // Arrange + Artist artist = CreateDomainArtist(); + ArtistMetadataDto dto = _artistMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]); + + // Act + Result result = dto.ApplyTo(artist, []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + } + + /// + /// Creates a domain artist that owns a single album, which in turn owns a single track. + /// + /// The created domain artist. + private Artist CreateDomainArtist() + { + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity albumEntity = _albumEntityFixture.Create( + id: albumId, + libraryId: libraryId, + tracks: [_trackEntityFixture.Create(albumId: albumId, libraryId: libraryId)]); + ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); + return artistEntity.ToDomainEntity().Value; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMappingTests.cs index 9382e008..7ac75599 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMappingTests.cs @@ -38,7 +38,7 @@ public class UpdateArtistAlbumRequestMappingTests Assert.Equal(request.Metadata, result.Metadata); Assert.Equal(request.MediaFormat, result.MediaFormat); Assert.Equal(request.Barcode, result.Barcode); - Assert.Equal(request.CatalogNumber, result.CatalogNumber); + Assert.Equal(request.CatalogNumbers, result.CatalogNumbers); Assert.Equal(request.MusicBrainzReleaseId, result.MusicBrainzReleaseId); Assert.Equal(request.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId); Assert.Equal(request.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId); @@ -84,7 +84,7 @@ public class UpdateArtistAlbumRequestMappingTests includeAlbumId: false, includeMediaFormat: false, includeBarcode: false, - includeCatalogNumber: false, + includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false, @@ -98,7 +98,7 @@ public class UpdateArtistAlbumRequestMappingTests Assert.Null(result.AlbumId); Assert.Null(result.MediaFormat); Assert.Null(result.Barcode); - Assert.Null(result.CatalogNumber); + Assert.Null(result.CatalogNumbers); Assert.Null(result.MusicBrainzReleaseId); Assert.Null(result.MusicBrainzReleaseGroupId); Assert.Null(result.MusicBrainzReleaseArtistId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs index 907a816d..a963e40a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs @@ -33,7 +33,8 @@ public class UpdateArtistCommandMappingTests private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly TrackEntityFixture _trackEntityFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); [Fact] @@ -56,7 +57,7 @@ public class UpdateArtistCommandMappingTests // Assert Assert.False(result.IsFailure); Assert.Same(artist, result.Value); - Assert.Equal(command.Name, result.Value.Name); + Assert.Equal(command.Metadata!.Name, result.Value.Name); Assert.True(result.Value.Website.HasValue); Assert.Equal(command.Website, result.Value.Website.Value); Assert.True(result.Value.MusicBrainzArtistId.HasValue); @@ -90,7 +91,6 @@ public class UpdateArtistCommandMappingTests includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, - includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false, contributors: [], @@ -134,7 +134,7 @@ public class UpdateArtistCommandMappingTests UpdateArtistCommand command = _updateArtistCommandFixture.Create( libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), - name: string.Empty, + metadata: _musicArtistMetadataDtoFixture.Create(name: string.Empty), albums: [albumCommand]); // Act @@ -153,7 +153,7 @@ public class UpdateArtistCommandMappingTests (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); AddAlbumCommand invalidAlbum = _addAlbumCommandFixture.Create( albumId: albumId, - metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); UpdateArtistCommand command = _updateArtistCommandFixture.Create( libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMappingTests.cs index c0409b09..fde91dc7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMappingTests.cs @@ -32,7 +32,7 @@ public class UpdateArtistRequestMappingTests Assert.NotNull(result); Assert.Equal(libraryId.ToString(), result.LibraryId); Assert.Equal(artistId.ToString(), result.ArtistId); - Assert.Equal(request.Name, result.Name); + Assert.Equal(request.Metadata!.Name, result.Metadata!.Name); Assert.Equal(request.Website, result.Website); Assert.Equal(request.MusicBrainzArtistId, result.MusicBrainzArtistId); Assert.Equal(request.Contributors, result.Contributors); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs index 8b71261a..a2fadffb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs @@ -19,7 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary. public class UpdateArtistTrackRequestMappingTests { private readonly UpdateArtistTrackRequestFixture _updateArtistTrackRequestFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); [Fact] public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() @@ -48,7 +48,6 @@ public class UpdateArtistTrackRequestMappingTests Assert.Equal(request.Work, result.Work); Assert.Equal(request.MusicBrainzRecordingId, result.MusicBrainzRecordingId); Assert.Equal(request.MusicBrainzTrackId, result.MusicBrainzTrackId); - Assert.Equal(request.MusicBrainzWorkId, result.MusicBrainzWorkId); Assert.Equal(request.Moods, result.Moods); Assert.Equal(request.Isrcs, result.Isrcs); Assert.Equal(request.Contributors, result.Contributors); @@ -62,7 +61,7 @@ public class UpdateArtistTrackRequestMappingTests // Arrange UpdateArtistTrackRequest request = _updateArtistTrackRequestFixture.Create( path: "/music/queen/bohemian-rhapsody.flac", - metadata: _audioMetadataDtoFixture.Create(title: "Love of My Life"), + metadata: _musicTrackMetadataDtoFixture.Create(title: "Love of My Life"), includeDiscNumber: false, includeScript: false, includeKey: false, @@ -70,7 +69,6 @@ public class UpdateArtistTrackRequestMappingTests includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, - includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false, includeTrackId: false); @@ -89,7 +87,6 @@ public class UpdateArtistTrackRequestMappingTests Assert.Null(result.Work); Assert.Null(result.MusicBrainzRecordingId); Assert.Null(result.MusicBrainzTrackId); - Assert.Null(result.MusicBrainzWorkId); Assert.Null(result.Moods); Assert.Null(result.Isrcs); Assert.Null(result.TrackId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/ArtistAliasEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/ArtistAliasEntityMappingTests.cs new file mode 100644 index 00000000..5922a39f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/ArtistAliasEntityMappingTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistAliasEntityMappingTests +{ + private readonly ArtistAliasEntityFixture _artistAliasEntityFixture = new(); + + [Fact] + public void ToDomainValueObject_WhenMappingValidArtistAliasEntity_ShouldMapCorrectly() + { + // Arrange + ArtistAliasEntity entity = _artistAliasEntityFixture.Create(name: "Freddie Mercury", isPrimary: true); + + // Act + Result result = entity.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Freddie Mercury", result.Value.Name); + Assert.True(result.Value.IsPrimary); + } + + [Theory] + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void ToDomainValueObject_WhenNameIsEmpty_ShouldReturnError(string name) + { + // Arrange + ArtistAliasEntity entity = _artistAliasEntityFixture.Create(name: name); + + // Act + Result result = entity.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistAliasNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainValueObjects_WhenMappingMultipleValidEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _artistAliasEntityFixture.CreateMany(2); + + // Act + Result> result = entities.ToDomainValueObjects(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(entities.Count, result.Value.Count); + for (int index = 0; index < entities.Count; index++) + Assert.Equal(entities[index].Name, result.Value[index].Name); + } + + [Fact] + public void ToDomainValueObjects_WhenAnEntityIsInvalid_ShouldReturnError() + { + // Arrange + List entities = + [ + _artistAliasEntityFixture.Create(name: "Freddie Mercury"), + _artistAliasEntityFixture.Create(name: string.Empty) + ]; + + // Act + Result> result = entities.ToDomainValueObjects(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistAliasNameCannotBeEmpty, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMappingTests.cs index b77ec6ab..776cbc78 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMappingTests.cs @@ -21,13 +21,13 @@ public class AudioRatingDtoMappingTests private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingCompleteAudioRatingDto_ShouldMapAllPropertiesCorrectly() + public void ToDomainValueObject_WhenMappingCompleteAudioRatingDto_ShouldMapAllPropertiesCorrectly() { // Arrange AudioRatingDto dto = _audioRatingDtoFixture.Create(); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -41,13 +41,13 @@ public class AudioRatingDtoMappingTests } [Fact] - public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() + public void ToDomainValueObject_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() { // Arrange AudioRatingDto dto = _audioRatingDtoFixture.Create(includeSource: false, includeVoteCount: false); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -58,13 +58,13 @@ public class AudioRatingDtoMappingTests } [Fact] - public void ToDomainEntity_WhenValueIsGreaterThanMaxValue_ShouldReturnError() + public void ToDomainValueObject_WhenValueIsGreaterThanMaxValue_ShouldReturnError() { // Arrange AudioRatingDto dto = _audioRatingDtoFixture.Create(value: 10, maxValue: 5); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -72,13 +72,13 @@ public class AudioRatingDtoMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidAudioRatingDtos_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidAudioRatingDtos_ShouldMapAllCorrectly() { // Arrange List dtos = _audioRatingDtoFixture.CreateMany(2); // Act - List> results = [.. dtos.ToDomainEntities()]; + List> results = [.. dtos.ToDomainValueObjects()]; // Assert Assert.Equal(dtos.Count, results.Count); @@ -91,7 +91,7 @@ public class AudioRatingDtoMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMixedValidAndInvalidAudioRatingDtos_ShouldReturnMixedResults() + public void ToDomainValueObjects_WhenMappingMixedValidAndInvalidAudioRatingDtos_ShouldReturnMixedResults() { // Arrange List dtos = @@ -102,7 +102,7 @@ public class AudioRatingDtoMappingTests ]; // Act - List> results = [.. dtos.ToDomainEntities()]; + List> results = [.. dtos.ToDomainValueObjects()]; // Assert Assert.Equal(dtos.Count, results.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMappingTests.cs index 9f1ac27b..039ae902 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMappingTests.cs @@ -75,13 +75,13 @@ public class AudioRatingEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingValidAudioRatingEntity_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidAudioRatingEntity_ShouldMapCorrectly() { // Arrange AudioRatingEntity entity = _audioRatingEntityFixture.Create(); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -95,13 +95,13 @@ public class AudioRatingEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingAudioRatingEntityWithNulls_ShouldMapToDefaults() + public void ToDomainValueObject_WhenMappingAudioRatingEntityWithNulls_ShouldMapToDefaults() { // Arrange AudioRatingEntity entity = _audioRatingEntityFixture.Create(includeValue: false, includeMaxValue: false, includeSource: false, includeVoteCount: false); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -112,13 +112,13 @@ public class AudioRatingEntityMappingTests } [Fact] - public void ToDomainEntity_WhenValueIsGreaterThanMaxValue_ShouldReturnError() + public void ToDomainValueObject_WhenValueIsGreaterThanMaxValue_ShouldReturnError() { // Arrange AudioRatingEntity entity = _audioRatingEntityFixture.Create(value: 6, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 10); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -126,13 +126,13 @@ public class AudioRatingEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidAudioRatingEntities_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidAudioRatingEntities_ShouldMapAllCorrectly() { // Arrange List entities = _audioRatingEntityFixture.CreateMany(2); // Act - List> results = [.. entities.ToDomainEntities()]; + List> results = [.. entities.ToDomainValueObjects()]; // Assert Assert.Equal(entities.Count, results.Count); @@ -145,7 +145,7 @@ public class AudioRatingEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMixedValidAndInvalidAudioRatingEntities_ShouldReturnMixedResults() + public void ToDomainValueObjects_WhenMappingMixedValidAndInvalidAudioRatingEntities_ShouldReturnMixedResults() { // Arrange List entities = @@ -156,7 +156,7 @@ public class AudioRatingEntityMappingTests ]; // Act - List> results = [.. entities.ToDomainEntities()]; + List> results = [.. entities.ToDomainValueObjects()]; // Assert Assert.Equal(entities.Count, results.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMappingTests.cs index 067c62d7..a3049af4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMappingTests.cs @@ -21,13 +21,13 @@ public class IsrcDtoMappingTests private readonly IsrcDtoFixture _isrcDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingValidIsrcDto_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidIsrcDto_ShouldMapCorrectly() { // Arrange IsrcDto dto = _isrcDtoFixture.Create(); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -36,13 +36,13 @@ public class IsrcDtoMappingTests } [Fact] - public void ToDomainEntity_WhenMappingLowercaseIsrcDto_ShouldNormalizeTheValue() + public void ToDomainValueObject_WhenMappingLowercaseIsrcDto_ShouldNormalizeTheValue() { // Arrange IsrcDto dto = _isrcDtoFixture.Create(value: "gbum71029604"); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -53,13 +53,13 @@ public class IsrcDtoMappingTests [InlineData(null)] // missing value [InlineData("")] // empty value [InlineData(" ")] // whitespace value - public void ToDomainEntity_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value) + public void ToDomainValueObject_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value) { // Arrange IsrcDto dto = _isrcDtoFixture.Create(value: value, includeValue: value is not null); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -72,13 +72,13 @@ public class IsrcDtoMappingTests [InlineData("GBUM71029604X")] // too long [InlineData("1BUM71029604")] // country code is not two letters [InlineData("GBUM7102960A")] // designation code is not all digits - public void ToDomainEntity_WhenValueIsMalformed_ShouldReturnError(string value) + public void ToDomainValueObject_WhenValueIsMalformed_ShouldReturnError(string value) { // Arrange IsrcDto dto = _isrcDtoFixture.Create(value: value); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -86,13 +86,13 @@ public class IsrcDtoMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidIsrcDtos_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidIsrcDtos_ShouldMapAllCorrectly() { // Arrange List dtos = _isrcDtoFixture.CreateMany(2); // Act - List> results = [.. dtos.ToDomainEntities()]; + List> results = [.. dtos.ToDomainValueObjects()]; // Assert Assert.Equal(dtos.Count, results.Count); @@ -104,7 +104,7 @@ public class IsrcDtoMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMixedValidAndInvalidIsrcDtos_ShouldReturnMixedResults() + public void ToDomainValueObjects_WhenMappingMixedValidAndInvalidIsrcDtos_ShouldReturnMixedResults() { // Arrange List dtos = @@ -115,7 +115,7 @@ public class IsrcDtoMappingTests ]; // Act - List> results = [.. dtos.ToDomainEntities()]; + List> results = [.. dtos.ToDomainValueObjects()]; // Assert Assert.Equal(dtos.Count, results.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMappingTests.cs index 83acca73..2408a577 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMappingTests.cs @@ -51,13 +51,13 @@ public class IsrcEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingValidTrackIsrcEntity_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidTrackIsrcEntity_ShouldMapCorrectly() { // Arrange TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: "GBUM71029604"); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -68,13 +68,13 @@ public class IsrcEntityMappingTests [Theory] [InlineData("")] // empty value [InlineData(" ")] // whitespace value - public void ToDomainEntity_WhenValueIsWhitespace_ShouldReturnError(string value) + public void ToDomainValueObject_WhenValueIsWhitespace_ShouldReturnError(string value) { // Arrange TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: value); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -82,13 +82,13 @@ public class IsrcEntityMappingTests } [Fact] - public void ToDomainEntity_WhenValueIsMalformed_ShouldReturnError() + public void ToDomainValueObject_WhenValueIsMalformed_ShouldReturnError() { // Arrange TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: "not-an-isrc"); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -96,13 +96,13 @@ public class IsrcEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidTrackIsrcEntities_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidTrackIsrcEntities_ShouldMapAllCorrectly() { // Arrange List entities = _trackIsrcEntityFixture.CreateMany(2); // Act - List> results = [.. entities.ToDomainEntities()]; + List> results = [.. entities.ToDomainValueObjects()]; // Assert Assert.Equal(entities.Count, results.Count); @@ -114,7 +114,7 @@ public class IsrcEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMixedValidAndInvalidTrackIsrcEntities_ShouldReturnMixedResults() + public void ToDomainValueObjects_WhenMappingMixedValidAndInvalidTrackIsrcEntities_ShouldReturnMixedResults() { // Arrange List entities = @@ -125,7 +125,7 @@ public class IsrcEntityMappingTests ]; // Act - List> results = [.. entities.ToDomainEntities()]; + List> results = [.. entities.ToDomainValueObjects()]; // Assert Assert.Equal(entities.Count, results.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMappingTests.cs index e0375340..1798a966 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMappingTests.cs @@ -21,13 +21,13 @@ public class MoodDtoMappingTests private readonly MoodDtoFixture _moodDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingValidMoodDto_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidMoodDto_ShouldMapCorrectly() { // Arrange MoodDto dto = _moodDtoFixture.Create(name: " Calm "); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -39,13 +39,13 @@ public class MoodDtoMappingTests [InlineData(null)] // missing name [InlineData("")] // empty name [InlineData(" ")] // whitespace name - public void ToDomainEntity_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + public void ToDomainValueObject_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) { // Arrange MoodDto dto = _moodDtoFixture.Create(name: name, includeName: name is not null); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -53,13 +53,13 @@ public class MoodDtoMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidMoodDtos_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidMoodDtos_ShouldMapAllCorrectly() { // Arrange List dtos = _moodDtoFixture.CreateMany(2); // Act - List> results = [.. dtos.ToDomainEntities()]; + List> results = [.. dtos.ToDomainValueObjects()]; // Assert Assert.Equal(dtos.Count, results.Count); @@ -71,7 +71,7 @@ public class MoodDtoMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMixedValidAndInvalidMoodDtos_ShouldReturnMixedResults() + public void ToDomainValueObjects_WhenMappingMixedValidAndInvalidMoodDtos_ShouldReturnMixedResults() { // Arrange List dtos = @@ -82,7 +82,7 @@ public class MoodDtoMappingTests ]; // Act - List> results = [.. dtos.ToDomainEntities()]; + List> results = [.. dtos.ToDomainValueObjects()]; // Assert Assert.Equal(dtos.Count, results.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMappingTests.cs index b8490ceb..8c6ad9f6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMappingTests.cs @@ -51,13 +51,13 @@ public class MoodEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingValidTrackMoodEntity_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidTrackMoodEntity_ShouldMapCorrectly() { // Arrange TrackMoodEntity entity = _trackMoodEntityFixture.Create(); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -68,13 +68,13 @@ public class MoodEntityMappingTests [Theory] [InlineData("")] // empty name [InlineData(" ")] // whitespace name - public void ToDomainEntity_WhenNameIsWhitespace_ShouldReturnError(string name) + public void ToDomainValueObject_WhenNameIsWhitespace_ShouldReturnError(string name) { // Arrange TrackMoodEntity entity = _trackMoodEntityFixture.Create(name: name); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -82,13 +82,13 @@ public class MoodEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidTrackMoodEntities_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidTrackMoodEntities_ShouldMapAllCorrectly() { // Arrange List entities = _trackMoodEntityFixture.CreateMany(2); // Act - List> results = [.. entities.ToDomainEntities()]; + List> results = [.. entities.ToDomainValueObjects()]; // Assert Assert.Equal(entities.Count, results.Count); @@ -100,7 +100,7 @@ public class MoodEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMixedValidAndInvalidTrackMoodEntities_ShouldReturnMixedResults() + public void ToDomainValueObjects_WhenMappingMixedValidAndInvalidTrackMoodEntities_ShouldReturnMixedResults() { // Arrange List entities = @@ -111,7 +111,7 @@ public class MoodEntityMappingTests ]; // Act - List> results = [.. entities.ToDomainEntities()]; + List> results = [.. entities.ToDomainValueObjects()]; // Assert Assert.Equal(entities.Count, results.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaDtoMappingTests.cs new file mode 100644 index 00000000..39431223 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaDtoMappingTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicAreaDtoMappingTests +{ + private readonly MusicAreaDtoFixture _musicAreaDtoFixture = new(); + + [Fact] + public void ToDomainValueObject_WhenMappingValidMusicAreaDto_ShouldMapCorrectly() + { + // Arrange + MusicAreaDto dto = _musicAreaDtoFixture.Create(name: "United Kingdom", iso3166Code: "GB"); + + // Act + Result> result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.True(result.Value.HasValue); + MusicArea area = result.Value.Value; + Assert.Equal(dto.MusicBrainzAreaId, area.MusicBrainzAreaId.Value); + Assert.Equal("United Kingdom", area.Name); + Assert.Equal("GB", area.Iso3166Code.Value); + } + + [Fact] + public void ToDomainValueObject_WhenAreaDtoIsNull_ShouldReturnNoArea() + { + // Arrange + MusicAreaDto? dto = null; + + // Act + Result> result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.HasValue); + } + + [Fact] + public void ToDomainValueObject_WhenMusicBrainzAreaIdIsMissing_ShouldReturnNoArea() + { + // Arrange + MusicAreaDto dto = _musicAreaDtoFixture.Create(includeMusicBrainzAreaId: false); + + // Act + Result> result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.HasValue); + } + + [Theory] + [InlineData(null)] // missing name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void ToDomainValueObject_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + { + // Arrange + MusicAreaDto dto = _musicAreaDtoFixture.Create(name: name, includeName: name is not null); + + // Act + Result> result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AreaNameCannotBeEmpty, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaEntityMappingTests.cs new file mode 100644 index 00000000..060be802 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaEntityMappingTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicAreaEntityMappingTests +{ + private readonly MusicAreaEntityFixture _musicAreaEntityFixture = new(); + + [Fact] + public void ToDomainValueObject_WhenMappingValidMusicAreaEntity_ShouldMapCorrectly() + { + // Arrange + MusicAreaEntity entity = _musicAreaEntityFixture.Create(name: "United Kingdom", iso3166Code: "GB"); + + // Act + Result result = entity.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(entity.MusicBrainzAreaId, result.Value.MusicBrainzAreaId.Value); + Assert.Equal("United Kingdom", result.Value.Name); + Assert.Equal("GB", result.Value.Iso3166Code.Value); + } + + [Theory] + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void ToDomainValueObject_WhenNameIsEmpty_ShouldReturnError(string name) + { + // Arrange + MusicAreaEntity entity = _musicAreaEntityFixture.Create(name: name); + + // Act + Result result = entity.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AreaNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToResponse_WhenEntityIsNull_ShouldReturnNull() + { + // Arrange + MusicAreaEntity? entity = null; + + // Act + MusicAreaDto? result = entity.ToResponse(); + + // Assert + Assert.Null(result); + } + + [Fact] + public void ToResponse_WhenMappingValidEntity_ShouldMapCorrectly() + { + // Arrange + MusicAreaEntity entity = _musicAreaEntityFixture.Create(name: "United Kingdom", iso3166Code: "GB"); + + // Act + MusicAreaDto? result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.MusicBrainzAreaId, result!.MusicBrainzAreaId); + Assert.Equal("United Kingdom", result.Name); + Assert.Equal("GB", result.Iso3166Code); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaMappingTests.cs new file mode 100644 index 00000000..d184be14 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicAreaMappingTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicAreaMappingTests +{ + private readonly MusicAreaFixture _musicAreaFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingValidMusicArea_ShouldMapCorrectly() + { + // Arrange + MusicArea area = _musicAreaFixture.Create(name: "United Kingdom", iso3166Code: Optional.Some("GB")); + + // Act + MusicAreaEntity result = area.ToRepositoryEntity(); + + // Assert + Assert.Equal(area.MusicBrainzAreaId.Value, result.MusicBrainzAreaId); + Assert.Equal("United Kingdom", result.Name); + Assert.Equal("GB", result.Iso3166Code); + } + + [Fact] + public void ToRepositoryEntity_WhenOptionalValuesAreAbsent_ShouldMapThemToNull() + { + // Arrange + MusicArea area = _musicAreaFixture.Create( + sortName: Optional.None(), + disambiguation: Optional.None(), + type: Optional.None(), + iso3166Code: Optional.None()); + + // Act + MusicAreaEntity result = area.ToRepositoryEntity(); + + // Assert + Assert.Null(result.SortName); + Assert.Null(result.Disambiguation); + Assert.Null(result.Type); + Assert.Null(result.Iso3166Code); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasDtoMappingTests.cs new file mode 100644 index 00000000..fe8d7b0e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasDtoMappingTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtistAliasDtoMappingTests +{ + private readonly MusicArtistAliasDtoFixture _musicArtistAliasDtoFixture = new(); + + [Fact] + public void ToDomainValueObject_WhenMappingValidMusicArtistAliasDto_ShouldMapCorrectly() + { + // Arrange + MusicArtistAliasDto dto = _musicArtistAliasDtoFixture.Create(name: "Freddie Mercury", isPrimary: true); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Freddie Mercury", result.Value.Name); + Assert.True(result.Value.IsPrimary); + } + + [Theory] + [InlineData(null)] // missing name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void ToDomainValueObject_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + { + // Arrange + MusicArtistAliasDto dto = _musicArtistAliasDtoFixture.Create(name: name, includeName: name is not null); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistAliasNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainValueObjects_WhenMappingMultipleValidAliasDtos_ShouldMapAllCorrectly() + { + // Arrange + List dtos = _musicArtistAliasDtoFixture.CreateMany(2); + + // Act + Result> result = dtos.ToDomainValueObjects(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(dtos.Count, result.Value.Count); + for (int index = 0; index < dtos.Count; index++) + Assert.Equal(dtos[index].Name, result.Value[index].Name); + } + + [Fact] + public void ToDomainValueObjects_WhenAliasDtosIsNull_ShouldReturnAnEmptyList() + { + // Arrange + IEnumerable? dtos = null; + + // Act + Result> result = dtos.ToDomainValueObjects(); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public void ToDomainValueObjects_WhenAnAliasIsInvalid_ShouldReturnError() + { + // Arrange + List dtos = + [ + _musicArtistAliasDtoFixture.Create(name: "Freddie Mercury"), + _musicArtistAliasDtoFixture.Create(name: string.Empty, includeName: true) + ]; + + // Act + Result> result = dtos.ToDomainValueObjects(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistAliasNameCannotBeEmpty, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasMappingTests.cs new file mode 100644 index 00000000..33804cbd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MusicArtistAliasMappingTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtistAliasMappingTests +{ + private readonly MusicArtistAliasFixture _musicArtistAliasFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingValidMusicArtistAlias_ShouldMapCorrectly() + { + // Arrange + MusicArtistAlias alias = _musicArtistAliasFixture.Create(name: "Freddie Mercury", isPrimary: true); + + // Act + ArtistAliasEntity result = alias.ToRepositoryEntity(); + + // Assert + Assert.Equal("Freddie Mercury", result.Name); + Assert.True(result.IsPrimary); + } + + [Fact] + public void ToRepositoryEntity_WhenOptionalValuesAreAbsent_ShouldMapThemToNull() + { + // Arrange + MusicArtistAlias alias = _musicArtistAliasFixture.Create( + sortName: Optional.None(), + type: Optional.None(), + locale: Optional.None(), + beginDate: Optional.None(), + endDate: Optional.None()); + + // Act + ArtistAliasEntity result = alias.ToRepositoryEntity(); + + // Assert + Assert.Null(result.SortName); + Assert.Null(result.Type); + Assert.Null(result.Locale); + Assert.Null(result.BeginDate); + Assert.Null(result.EndDate); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingMultipleAliases_ShouldMapAllCorrectly() + { + // Arrange + List aliases = _musicArtistAliasFixture.CreateMany(2); + + // Act + List result = aliases.ToRepositoryEntities(); + + // Assert + Assert.Equal(aliases.Count, result.Count); + for (int index = 0; index < aliases.Count; index++) + Assert.Equal(aliases[index].Name, result[index].Name); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMappingTests.cs index edf5f0fd..69b92405 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMappingTests.cs @@ -23,7 +23,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary. public class AddTrackCommandMappingTests { private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly MoodDtoFixture _moodDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); @@ -47,10 +47,10 @@ public class AddTrackCommandMappingTests Assert.Equal(command.Script, result.Value.Script.Value); Assert.Equal(command.Key, result.Value.Key.Value); Assert.Equal(command.Bpm, result.Value.Bpm.Value); - Assert.Equal(command.Work, result.Value.Work.Value); + Assert.Equal(command.Work!.Title, result.Value.Work.Value.Title); Assert.Equal(command.MusicBrainzRecordingId, result.Value.MusicBrainzRecordingId.Value.Value); Assert.Equal(command.MusicBrainzTrackId, result.Value.MusicBrainzTrackId.Value.Value); - Assert.Equal(command.MusicBrainzWorkId, result.Value.MusicBrainzWorkId.Value.Value); + Assert.Equal(command.Work!.MusicBrainzWorkId, result.Value.Work.Value.MusicBrainzWorkId.Value); Assert.Equal(command.Moods!.Count, result.Value.Moods.Count); Assert.Equal(command.Isrcs!.Count, result.Value.Isrcs.Count); Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count); @@ -90,7 +90,7 @@ public class AddTrackCommandMappingTests public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act Result result = command.ToDomainEntity(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMappingTests.cs index 3cedb065..adbb24ee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMappingTests.cs @@ -19,7 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary. public class AddTrackRequestMappingTests { private readonly AddTrackRequestFixture _addTrackRequestFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); [Fact] public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() @@ -48,7 +48,6 @@ public class AddTrackRequestMappingTests Assert.Equal(request.Work, result.Work); Assert.Equal(request.MusicBrainzRecordingId, result.MusicBrainzRecordingId); Assert.Equal(request.MusicBrainzTrackId, result.MusicBrainzTrackId); - Assert.Equal(request.MusicBrainzWorkId, result.MusicBrainzWorkId); Assert.Equal(request.Moods, result.Moods); Assert.Equal(request.Isrcs, result.Isrcs); Assert.Equal(request.Contributors, result.Contributors); @@ -62,7 +61,7 @@ public class AddTrackRequestMappingTests // Arrange AddTrackRequest request = _addTrackRequestFixture.Create( path: "/music/queen/bohemian-rhapsody.flac", - metadata: _audioMetadataDtoFixture.Create(title: "Love of My Life"), + metadata: _musicTrackMetadataDtoFixture.Create(title: "Love of My Life"), includeDiscNumber: false, includeScript: false, includeKey: false, @@ -70,7 +69,6 @@ public class AddTrackRequestMappingTests includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, - includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); @@ -88,7 +86,6 @@ public class AddTrackRequestMappingTests Assert.Null(result.Work); Assert.Null(result.MusicBrainzRecordingId); Assert.Null(result.MusicBrainzTrackId); - Assert.Null(result.MusicBrainzWorkId); Assert.Null(result.Moods); Assert.Null(result.Isrcs); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.cs index 64490585..a0f88af7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.cs @@ -1,13 +1,18 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; -using Lumina.Contracts.DTO.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; -using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion @@ -21,167 +26,114 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary. public class AudioMetadataDtoMappingTests { private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); - private readonly GenreDtoFixture _genreDtoFixture = new(); - private readonly TagDtoFixture _tagDtoFixture = new(); - private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); - private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() + public void ApplyTo_WhenMappingCompleteDto_ShouldApplyAllPropertiesCorrectly() { // Arrange + (Artist artist, Album album, Track track) = CreateDomainArtist(); AudioMetadataDto dto = _audioMetadataDtoFixture.Create(); + List contributors = _musicMediaContributorFixture.CreateMany(2); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, album, track, contributors); // Assert Assert.False(result.IsFailure); - AudioMetadata metadata = result.Value; - Assert.Equal(dto.Title, metadata.Title); - Assert.True(metadata.OriginalTitle.HasValue); - Assert.Equal(dto.OriginalTitle, metadata.OriginalTitle.Value); - Assert.True(metadata.Description.HasValue); - Assert.Equal(dto.Description, metadata.Description.Value); - Assert.True(metadata.ReleaseInfo.OriginalReleaseDate.HasValue); - Assert.Equal(dto.ReleaseInfo!.OriginalReleaseDate, metadata.ReleaseInfo.OriginalReleaseDate.Value); - Assert.True(metadata.ReleaseInfo.OriginalReleaseYear.HasValue); - Assert.Equal(dto.ReleaseInfo.OriginalReleaseYear, metadata.ReleaseInfo.OriginalReleaseYear.Value); - Assert.True(metadata.ReleaseInfo.ReReleaseDate.HasValue); - Assert.Equal(dto.ReleaseInfo.ReReleaseDate, metadata.ReleaseInfo.ReReleaseDate.Value); - Assert.True(metadata.ReleaseInfo.ReReleaseYear.HasValue); - Assert.Equal(dto.ReleaseInfo.ReReleaseYear, metadata.ReleaseInfo.ReReleaseYear.Value); - Assert.True(metadata.ReleaseInfo.ReleaseCountry.HasValue); - Assert.Equal(dto.ReleaseInfo.ReleaseCountry, metadata.ReleaseInfo.ReleaseCountry.Value); - Assert.True(metadata.ReleaseInfo.ReleaseVersion.HasValue); - Assert.Equal(dto.ReleaseInfo.ReleaseVersion, metadata.ReleaseInfo.ReleaseVersion.Value); - Assert.True(metadata.Language.HasValue); - Assert.Equal(dto.Language!.LanguageCode!.ToLowerInvariant(), metadata.Language.Value.LanguageCode); - Assert.Equal(dto.Language.LanguageName, metadata.Language.Value.LanguageName); - Assert.Equal(dto.Language.NativeName, metadata.Language.Value.NativeName.Value); - Assert.True(metadata.OriginalLanguage.HasValue); - Assert.Equal(dto.OriginalLanguage!.LanguageCode!.ToLowerInvariant(), metadata.OriginalLanguage.Value.LanguageCode); - Assert.Equal(dto.OriginalLanguage.LanguageName, metadata.OriginalLanguage.Value.LanguageName); - Assert.Equal(dto.OriginalLanguage.NativeName, metadata.OriginalLanguage.Value.NativeName.Value); - Assert.Equal(dto.DurationInSeconds, metadata.DurationInSeconds); - Assert.Equal(dto.SampleRate, metadata.SampleRate); - Assert.Equal(dto.Channels, metadata.Channels); - Assert.True(metadata.BitDepth.HasValue); - Assert.Equal(dto.BitDepth, metadata.BitDepth.Value); - Assert.True(metadata.AudioCodec.HasValue); - Assert.Equal(dto.AudioCodec, metadata.AudioCodec.Value); - Assert.True(metadata.Bitrate.HasValue); - Assert.Equal(dto.Bitrate, metadata.Bitrate.Value); - Assert.Equal(dto.Genres!.Select(genre => genre.Name), metadata.Genres.Select(genre => genre.Name)); - Assert.Equal(dto.Tags!.Select(tag => tag.Name), metadata.Tags.Select(tag => tag.Name)); + Assert.Equal(dto.Title, track.Metadata.Title); + Assert.Equal(dto.DurationInSeconds, track.Metadata.DurationInSeconds); + Assert.Equal(dto.SampleRate, track.Metadata.SampleRate); + Assert.Equal(dto.Channels, track.Metadata.Channels); + Assert.Equal(dto.BitDepth, track.Metadata.BitDepth.Value); + Assert.Equal(dto.AudioCodec, track.Metadata.AudioCodec.Value); + Assert.Equal(dto.Bitrate, track.Metadata.Bitrate.Value); + Assert.True(track.Script.HasValue); + Assert.Equal(dto.Script, track.Script.Value); + Assert.True(track.Key.HasValue); + Assert.Equal(dto.Key, track.Key.Value); + Assert.True(track.Bpm.HasValue); + Assert.Equal(dto.Bpm, track.Bpm.Value); + Assert.Equal(dto.IsVideo, track.IsVideo); + Assert.True(track.Work.HasValue); + Assert.Equal(dto.Work!.MusicBrainzWorkId, track.Work.Value.MusicBrainzWorkId.Value); + Assert.Equal(dto.Isrcs!.Count, track.Isrcs.Count); + Assert.Equal(dto.Moods!.Count, track.Moods.Count); + Assert.True(track.MusicBrainzRecordingId.HasValue); + Assert.Equal(dto.MusicBrainzRecordingId, track.MusicBrainzRecordingId.Value.Value); + Assert.True(track.MusicBrainzTrackId.HasValue); + Assert.Equal(dto.MusicBrainzTrackId, track.MusicBrainzTrackId.Value.Value); + Assert.Equal(contributors.Count, track.Contributors.Count); + Assert.Equal(dto.Ratings!.Count, track.Ratings.Count); } [Fact] - public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults() + public void ApplyTo_WhenProviderFieldsAreMissing_ShouldPreserveTheLocallyExtractedValues() { // Arrange + (Artist artist, Album album, Track track) = CreateDomainArtist(); + int storedDuration = track.Metadata.DurationInSeconds; + int storedSampleRate = track.Metadata.SampleRate; + int storedChannels = track.Metadata.Channels; + bool hadStoredWork = track.Work.HasValue; + int storedIsrcCount = track.Isrcs.Count; AudioMetadataDto dto = _audioMetadataDtoFixture.Create( - includeOriginalTitle: false, - includeDescription: false, - includeReleaseInfo: false, - includeLanguage: false, - includeOriginalLanguage: false, - includeTags: false, - includeGenres: false, includeDurationInSeconds: false, includeSampleRate: false, includeChannels: false, includeBitDepth: false, includeAudioCodec: false, - includeBitrate: false); + includeBitrate: false, + includeWork: false, + includeIsrcs: false, + includeMoods: false); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, album, track, []); // Assert Assert.False(result.IsFailure); - AudioMetadata metadata = result.Value; - Assert.Equal(dto.Title, metadata.Title); - Assert.False(metadata.OriginalTitle.HasValue); - Assert.False(metadata.Description.HasValue); - Assert.False(metadata.ReleaseInfo.OriginalReleaseDate.HasValue); - Assert.False(metadata.ReleaseInfo.OriginalReleaseYear.HasValue); - Assert.False(metadata.ReleaseInfo.ReReleaseDate.HasValue); - Assert.False(metadata.ReleaseInfo.ReReleaseYear.HasValue); - Assert.False(metadata.ReleaseInfo.ReleaseCountry.HasValue); - Assert.False(metadata.ReleaseInfo.ReleaseVersion.HasValue); - Assert.Equal(0, metadata.DurationInSeconds); - Assert.Equal(0, metadata.SampleRate); - Assert.Equal(0, metadata.Channels); - Assert.False(metadata.BitDepth.HasValue); - Assert.False(metadata.AudioCodec.HasValue); - Assert.False(metadata.Bitrate.HasValue); - Assert.False(metadata.Language.HasValue); - Assert.False(metadata.OriginalLanguage.HasValue); - Assert.Empty(metadata.Genres); - Assert.Empty(metadata.Tags); + Assert.Equal(storedDuration, track.Metadata.DurationInSeconds); + Assert.Equal(storedSampleRate, track.Metadata.SampleRate); + Assert.Equal(storedChannels, track.Metadata.Channels); + Assert.Equal(hadStoredWork, track.Work.HasValue); + Assert.Equal(storedIsrcCount, track.Isrcs.Count); } [Fact] - public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone() + public void ApplyTo_WhenTrackDoesNotBelongToAlbum_ShouldReturnTrackNotFound() { // Arrange - LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false); - AudioMetadataDto dto = _audioMetadataDtoFixture.Create( - language: incompleteLanguage, - originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false)); + (Artist artist, Album album, Track _) = CreateDomainArtist(); + (Artist _, Album _, Track foreignTrack) = CreateDomainArtist(); + AudioMetadataDto dto = _audioMetadataDtoFixture.Create(); // Act - Result result = dto.ToDomainEntity(); - - // Assert - Assert.False(result.IsFailure); - Assert.False(result.Value.Language.HasValue); - Assert.False(result.Value.OriginalLanguage.HasValue); - } - - [Fact] - public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError() - { - // Arrange - ReleaseInfoDto releaseInfo = _releaseInfoDtoFixture.Create( - originalReleaseDate: new DateOnly(2000, 1, 1), - originalReleaseYear: 1999); - AudioMetadataDto dto = _audioMetadataDtoFixture.Create(releaseInfo: releaseInfo); - - // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ApplyTo(artist, album, foreignTrack, []); // Assert Assert.True(result.IsFailure); - Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); } - [Fact] - public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + /// + /// Creates a domain artist that owns a single album, which in turn owns a single track. + /// + /// The created domain artist, together with its album and track. + private (Artist artist, Album album, Track track) CreateDomainArtist() { - // Arrange - AudioMetadataDto dto = _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]); - - // Act - Result result = dto.ToDomainEntity(); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); - } - - [Fact] - public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError() - { - // Arrange - AudioMetadataDto dto = _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]); - - // Act - Result result = dto.ToDomainEntity(); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError); + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity albumEntity = _albumEntityFixture.Create( + id: albumId, + libraryId: libraryId, + tracks: [_trackEntityFixture.Create(albumId: albumId, libraryId: libraryId)]); + ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); + Artist artist = artistEntity.ToDomainEntity().Value; + Album album = artist.Albums.First(); + return (artist, album, album.Tracks.First()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMappingTests.cs new file mode 100644 index 00000000..43fb03f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicTrackMetadataDtoMappingTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicTrackMetadataDtoMappingTests +{ + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + AudioMetadata metadata = result.Value; + Assert.Equal(dto.Title, metadata.Title); + Assert.True(metadata.OriginalTitle.HasValue); + Assert.Equal(dto.OriginalTitle, metadata.OriginalTitle.Value); + Assert.True(metadata.Description.HasValue); + Assert.Equal(dto.Description, metadata.Description.Value); + Assert.True(metadata.ReleaseInfo.OriginalReleaseDate.HasValue); + Assert.Equal(dto.ReleaseInfo!.OriginalReleaseDate, metadata.ReleaseInfo.OriginalReleaseDate.Value); + Assert.True(metadata.ReleaseInfo.OriginalReleaseYear.HasValue); + Assert.Equal(dto.ReleaseInfo.OriginalReleaseYear, metadata.ReleaseInfo.OriginalReleaseYear.Value); + Assert.True(metadata.ReleaseInfo.ReReleaseDate.HasValue); + Assert.Equal(dto.ReleaseInfo.ReReleaseDate, metadata.ReleaseInfo.ReReleaseDate.Value); + Assert.True(metadata.ReleaseInfo.ReReleaseYear.HasValue); + Assert.Equal(dto.ReleaseInfo.ReReleaseYear, metadata.ReleaseInfo.ReReleaseYear.Value); + Assert.True(metadata.ReleaseInfo.ReleaseCountry.HasValue); + Assert.Equal(dto.ReleaseInfo.ReleaseCountry, metadata.ReleaseInfo.ReleaseCountry.Value); + Assert.True(metadata.ReleaseInfo.ReleaseVersion.HasValue); + Assert.Equal(dto.ReleaseInfo.ReleaseVersion, metadata.ReleaseInfo.ReleaseVersion.Value); + Assert.True(metadata.Language.HasValue); + Assert.Equal(dto.Language!.LanguageCode!.ToLowerInvariant(), metadata.Language.Value.LanguageCode); + Assert.Equal(dto.Language.LanguageName, metadata.Language.Value.LanguageName); + Assert.Equal(dto.Language.NativeName, metadata.Language.Value.NativeName.Value); + Assert.True(metadata.OriginalLanguage.HasValue); + Assert.Equal(dto.OriginalLanguage!.LanguageCode!.ToLowerInvariant(), metadata.OriginalLanguage.Value.LanguageCode); + Assert.Equal(dto.OriginalLanguage.LanguageName, metadata.OriginalLanguage.Value.LanguageName); + Assert.Equal(dto.OriginalLanguage.NativeName, metadata.OriginalLanguage.Value.NativeName.Value); + Assert.Equal(dto.DurationInSeconds, metadata.DurationInSeconds); + Assert.Equal(dto.SampleRate, metadata.SampleRate); + Assert.Equal(dto.Channels, metadata.Channels); + Assert.True(metadata.BitDepth.HasValue); + Assert.Equal(dto.BitDepth, metadata.BitDepth.Value); + Assert.True(metadata.AudioCodec.HasValue); + Assert.Equal(dto.AudioCodec, metadata.AudioCodec.Value); + Assert.True(metadata.Bitrate.HasValue); + Assert.Equal(dto.Bitrate, metadata.Bitrate.Value); + Assert.Equal(dto.Genres!.Select(genre => genre.Name), metadata.Genres.Select(genre => genre.Name)); + Assert.Equal(dto.Tags!.Select(tag => tag.Name), metadata.Tags.Select(tag => tag.Name)); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults() + { + // Arrange + MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create( + includeOriginalTitle: false, + includeDescription: false, + includeReleaseInfo: false, + includeLanguage: false, + includeOriginalLanguage: false, + includeTags: false, + includeGenres: false, + includeDurationInSeconds: false, + includeSampleRate: false, + includeChannels: false, + includeBitDepth: false, + includeAudioCodec: false, + includeBitrate: false); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + AudioMetadata metadata = result.Value; + Assert.Equal(dto.Title, metadata.Title); + Assert.False(metadata.OriginalTitle.HasValue); + Assert.False(metadata.Description.HasValue); + Assert.False(metadata.ReleaseInfo.OriginalReleaseDate.HasValue); + Assert.False(metadata.ReleaseInfo.OriginalReleaseYear.HasValue); + Assert.False(metadata.ReleaseInfo.ReReleaseDate.HasValue); + Assert.False(metadata.ReleaseInfo.ReReleaseYear.HasValue); + Assert.False(metadata.ReleaseInfo.ReleaseCountry.HasValue); + Assert.False(metadata.ReleaseInfo.ReleaseVersion.HasValue); + Assert.Equal(0, metadata.DurationInSeconds); + Assert.Equal(0, metadata.SampleRate); + Assert.Equal(0, metadata.Channels); + Assert.False(metadata.BitDepth.HasValue); + Assert.False(metadata.AudioCodec.HasValue); + Assert.False(metadata.Bitrate.HasValue); + Assert.False(metadata.Language.HasValue); + Assert.False(metadata.OriginalLanguage.HasValue); + Assert.Empty(metadata.Genres); + Assert.Empty(metadata.Tags); + } + + [Fact] + public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone() + { + // Arrange + LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false); + MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create( + language: incompleteLanguage, + originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false)); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Language.HasValue); + Assert.False(result.Value.OriginalLanguage.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError() + { + // Arrange + ReleaseInfoDto releaseInfo = _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(2000, 1, 1), + originalReleaseYear: 1999); + MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(releaseInfo: releaseInfo); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + { + // Arrange + MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError() + { + // Arrange + MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicWorkDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicWorkDtoMappingTests.cs new file mode 100644 index 00000000..4383b3c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/MusicWorkDtoMappingTests.cs @@ -0,0 +1,160 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicWorkDtoMappingTests +{ + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + MusicWorkDto dto = _musicWorkDtoFixture.Create(); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + MusicWork work = result.Value; + Assert.Equal(dto.MusicBrainzWorkId!.Value, work.MusicBrainzWorkId.Value); + Assert.Equal(dto.Title, work.Title); + Assert.True(work.Type.HasValue); + Assert.Equal(dto.Type, work.Type.Value); + Assert.Equal(dto.Languages!.Count, work.Languages.Count); + Assert.Equal(dto.Iswcs, work.Iswcs); + } + + [Fact] + public void ToDomainEntity_WhenLanguageIsMapped_ShouldLowercaseTheLanguageCode() + { + // Arrange + LanguageInfoDto language = _languageInfoDtoFixture.Create(languageCode: "EN", languageName: "English", nativeName: "English"); + MusicWorkDto dto = _musicWorkDtoFixture.Create(languages: [language]); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + LanguageInfo mappedLanguage = Assert.Single(result.Value.Languages); + Assert.Equal("en", mappedLanguage.LanguageCode); + Assert.Equal("English", mappedLanguage.LanguageName); + Assert.Equal("English", mappedLanguage.NativeName.Value); + } + + [Fact] + public void ToDomainEntity_WhenMusicBrainzWorkIdIsMissing_ShouldReturnError() + { + // Arrange + MusicWorkDto dto = _musicWorkDtoFixture.Create(includeMusicBrainzWorkId: false); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.MusicBrainzIdInvalidFormat, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenTitleIsMissing_ShouldReturnError() + { + // Arrange + MusicWorkDto dto = _musicWorkDtoFixture.Create(includeTitle: false); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.WorkTitleCannotBeEmpty, result.FirstError); + } + + [Theory] + [InlineData("")] // empty work title + [InlineData(" ")] // whitespace work title + public void ToDomainEntity_WhenTitleIsEmptyOrWhitespace_ShouldReturnError(string title) + { + // Arrange + MusicWorkDto dto = _musicWorkDtoFixture.Create(title: title); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.WorkTitleCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults() + { + // Arrange + MusicWorkDto dto = _musicWorkDtoFixture.Create( + includeType: false, + includeLanguages: false, + includeIswcs: false); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + MusicWork work = result.Value; + Assert.Equal(dto.Title, work.Title); + Assert.False(work.Type.HasValue); + Assert.Empty(work.Languages); + Assert.Empty(work.Iswcs); + } + + [Fact] + public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldSkipIt() + { + // Arrange + LanguageInfoDto languageWithoutCode = _languageInfoDtoFixture.Create(languageName: "English", includeLanguageCode: false); + LanguageInfoDto languageWithoutName = _languageInfoDtoFixture.Create(languageCode: "fr", includeLanguageName: false); + MusicWorkDto dto = _musicWorkDtoFixture.Create(languages: [languageWithoutCode, languageWithoutName]); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Languages); + } + + [Fact] + public void ToDomainEntity_WhenIswcsContainBlankValues_ShouldTrimThemAndSkipTheBlankOnes() + { + // Arrange + MusicWorkDto dto = _musicWorkDtoFixture.Create(iswcs: [" T1234567890 ", " ", ""]); + + // Act + Result result = dto.ToDomainValueObject(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["T1234567890"], result.Value.Iswcs); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs index 5d90ead0..bf746994 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs @@ -2,10 +2,13 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -26,6 +29,12 @@ public class TrackEntityMappingTests { private readonly TrackEntityFixture _trackEntityFixture = new(); private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); [Fact] public void ToDomainEntity_WhenMappingValidTrackEntity_ShouldMapAllPropertiesCorrectly() @@ -73,10 +82,10 @@ public class TrackEntityMappingTests Assert.Equal(entity.Script, track.Script.Value); Assert.Equal(entity.Key, track.Key.Value); Assert.Equal(entity.Bpm, track.Bpm.Value); - Assert.Equal(entity.Work, track.Work.Value); + Assert.Equal(entity.WorkTitle, track.Work.Value.Title); Assert.Equal(entity.MusicBrainzRecordingId, track.MusicBrainzRecordingId.Value.Value); Assert.Equal(entity.MusicBrainzTrackId, track.MusicBrainzTrackId.Value.Value); - Assert.Equal(entity.MusicBrainzWorkId, track.MusicBrainzWorkId.Value.Value); + Assert.Equal(entity.MusicBrainzWorkId, track.Work.Value.MusicBrainzWorkId.Value); Assert.Equal(entity.Moods.Select(mood => mood.Name), track.Moods.Select(mood => mood.Name)); Assert.Equal(entity.Isrcs.Select(isrc => isrc.Value), track.Isrcs.Select(isrc => isrc.Value)); Assert.Equal(entity.Ratings.Select(rating => rating.Value), track.Ratings.Select(rating => (decimal?)rating.Value)); @@ -107,7 +116,7 @@ public class TrackEntityMappingTests { // Arrange TrackEntity entity = _trackEntityFixture.Create(); - entity.Genres = [new GenreEntity(string.Empty)]; + entity.Genres = [_genreEntityFixture.Create(name: string.Empty)]; // Act Result result = entity.ToDomainEntity(); @@ -122,7 +131,7 @@ public class TrackEntityMappingTests { // Arrange TrackEntity entity = _trackEntityFixture.Create(); - entity.Tags = [new TagEntity(" ")]; + entity.Tags = [_tagEntityFixture.Create(name: " ")]; // Act Result result = entity.ToDomainEntity(); @@ -137,7 +146,7 @@ public class TrackEntityMappingTests { // Arrange TrackEntity entity = _trackEntityFixture.Create(); - entity.Moods = [new TrackMoodEntity(string.Empty)]; + entity.Moods = [_trackMoodEntityFixture.Create(name: string.Empty)]; // Act Result result = entity.ToDomainEntity(); @@ -152,7 +161,7 @@ public class TrackEntityMappingTests { // Arrange TrackEntity entity = _trackEntityFixture.Create(); - entity.Isrcs = [new TrackIsrcEntity("not-an-isrc")]; + entity.Isrcs = [_trackIsrcEntityFixture.Create(value: "not-an-isrc")]; // Act Result result = entity.ToDomainEntity(); @@ -222,16 +231,16 @@ public class TrackEntityMappingTests Assert.Equal(entity.Script, result.Script); Assert.Equal(entity.Key, result.Key); Assert.Equal(entity.Bpm, result.Bpm); - Assert.Equal(entity.Work, result.Work); + Assert.Equal(entity.WorkTitle, result.Work!.Title); Assert.Equal(entity.MusicBrainzRecordingId, result.MusicBrainzRecordingId); Assert.Equal(entity.MusicBrainzTrackId, result.MusicBrainzTrackId); - Assert.Equal(entity.MusicBrainzWorkId, result.MusicBrainzWorkId); + Assert.Equal(entity.MusicBrainzWorkId, result.Work!.MusicBrainzWorkId); Assert.Equal(entity.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(entity.UpdatedOnUtc, result.UpdatedOnUtc); Assert.Equal(entity.Moods.Select(mood => mood.Name), result.Moods!.Select(mood => mood.Name)); Assert.Equal(entity.Isrcs.Select(isrc => isrc.Value), result.Isrcs!.Select(isrc => isrc.Value)); - Assert.Equal(entity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role)), result.Contributors); - Assert.Equal(entity.Ratings.Select(rating => new AudioRatingDto(rating.Value, rating.MaxValue, rating.Source, rating.VoteCount)), result.Ratings); + Assert.Equal(entity.Contributors.Select(contributor => _mediaContributorReferenceDtoFixture.Create(contributorId: contributor.MediaContributorId, role: contributor.Role)), result.Contributors); + Assert.Equal(entity.Ratings.Select(rating => _audioRatingDtoFixture.Create(value: rating.Value, maxValue: rating.MaxValue, source: rating.Source, voteCount: rating.VoteCount)), result.Ratings); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs index f0d25362..0483a1f4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs @@ -74,10 +74,10 @@ public class TrackMappingTests Assert.Equal(track.Script.HasValue ? track.Script.Value : null, result.Script); Assert.Equal(track.Key.HasValue ? track.Key.Value : null, result.Key); Assert.Equal(track.Bpm.HasValue ? track.Bpm.Value : null, result.Bpm); - Assert.Equal(track.Work.HasValue ? track.Work.Value : null, result.Work); + Assert.Equal(track.Work.HasValue ? track.Work.Value.Title : null, result.WorkTitle); Assert.Equal(track.MusicBrainzRecordingId.HasValue ? track.MusicBrainzRecordingId.Value.Value : null, result.MusicBrainzRecordingId); Assert.Equal(track.MusicBrainzTrackId.HasValue ? track.MusicBrainzTrackId.Value.Value : null, result.MusicBrainzTrackId); - Assert.Equal(track.MusicBrainzWorkId.HasValue ? track.MusicBrainzWorkId.Value.Value : null, result.MusicBrainzWorkId); + Assert.Equal(track.Work.HasValue ? track.Work.Value.MusicBrainzWorkId.Value : null, result.MusicBrainzWorkId); Assert.Equal(track.Moods.ToRepositoryEntities(), result.Moods); Assert.Equal(track.Isrcs.ToRepositoryEntities(), result.Isrcs); Assert.Equal(track.Ratings.ToRepositoryEntities(), result.Ratings); @@ -141,12 +141,11 @@ public class TrackMappingTests script: Optional.None(), key: Optional.None(), bpm: Optional.None(), - work: Optional.None(), + work: Optional.None(), moods: [], isrcs: [], musicBrainzRecordingId: Optional.None(), musicBrainzTrackId: Optional.None(), - musicBrainzWorkId: Optional.None(), contributors: [], ratings: []); @@ -175,7 +174,7 @@ public class TrackMappingTests Assert.Null(result.Script); Assert.Null(result.Key); Assert.Null(result.Bpm); - Assert.Null(result.Work); + Assert.Null(result.WorkTitle); Assert.Null(result.MusicBrainzRecordingId); Assert.Null(result.MusicBrainzTrackId); Assert.Null(result.MusicBrainzWorkId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs index a88c1501..8146c73d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs @@ -32,7 +32,7 @@ public class UpdateTrackCommandMappingTests private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly TrackEntityFixture _trackEntityFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly MoodDtoFixture _moodDtoFixture = new(); private readonly IsrcDtoFixture _isrcDtoFixture = new(); @@ -67,10 +67,10 @@ public class UpdateTrackCommandMappingTests Assert.True(updatedTrack.Bpm.HasValue); Assert.Equal(command.Bpm, updatedTrack.Bpm.Value); Assert.True(updatedTrack.Work.HasValue); - Assert.Equal(command.Work, updatedTrack.Work.Value); + Assert.Equal(command.Work!.Title, updatedTrack.Work.Value.Title); Assert.Equal(command.MusicBrainzRecordingId, updatedTrack.MusicBrainzRecordingId.Value.Value); Assert.Equal(command.MusicBrainzTrackId, updatedTrack.MusicBrainzTrackId.Value.Value); - Assert.Equal(command.MusicBrainzWorkId, updatedTrack.MusicBrainzWorkId.Value.Value); + Assert.Equal(command.Work!.MusicBrainzWorkId, updatedTrack.Work.Value.MusicBrainzWorkId.Value); Assert.Equal(command.Moods!.Count, updatedTrack.Moods.Count); Assert.Equal(command.Isrcs!.Count, updatedTrack.Isrcs.Count); Assert.Equal(command.Contributors!.Count, updatedTrack.Contributors.Count); @@ -84,7 +84,7 @@ public class UpdateTrackCommandMappingTests Guid libraryId = Guid.NewGuid(); (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); string updatedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac"; - UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath, includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false, contributors: [], ratings: []); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath, includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false, contributors: [], ratings: []); // Act Result result = command.ToDomainEntity(artist); @@ -101,7 +101,6 @@ public class UpdateTrackCommandMappingTests Assert.False(updatedTrack.Work.HasValue); Assert.False(updatedTrack.MusicBrainzRecordingId.HasValue); Assert.False(updatedTrack.MusicBrainzTrackId.HasValue); - Assert.False(updatedTrack.MusicBrainzWorkId.HasValue); Assert.Empty(updatedTrack.Moods); Assert.Empty(updatedTrack.Isrcs); Assert.Empty(updatedTrack.Contributors); @@ -119,7 +118,7 @@ public class UpdateTrackCommandMappingTests artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), - metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act Result result = command.ToDomainEntity(artist); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs index 22308dc6..c19f7f36 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs @@ -48,7 +48,6 @@ public class UpdateTrackRequestMappingTests Assert.Equal(request.Work, result.Work); Assert.Equal(request.MusicBrainzRecordingId, result.MusicBrainzRecordingId); Assert.Equal(request.MusicBrainzTrackId, result.MusicBrainzTrackId); - Assert.Equal(request.MusicBrainzWorkId, result.MusicBrainzWorkId); Assert.Equal(request.Moods, result.Moods); Assert.Equal(request.Isrcs, result.Isrcs); Assert.Equal(request.Contributors, result.Contributors); @@ -71,7 +70,6 @@ public class UpdateTrackRequestMappingTests includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, - includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false, contributors: [], @@ -95,7 +93,6 @@ public class UpdateTrackRequestMappingTests Assert.Null(result.Work); Assert.Null(result.MusicBrainzRecordingId); Assert.Null(result.MusicBrainzTrackId); - Assert.Null(result.MusicBrainzWorkId); Assert.Null(result.Moods); Assert.Null(result.Isrcs); Assert.Empty(result.Contributors!); @@ -121,8 +118,7 @@ public class UpdateTrackRequestMappingTests includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, - includeMusicBrainzTrackId: false, - includeMusicBrainzWorkId: false); + includeMusicBrainzTrackId: false); // Act UpdateTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString(), trackId.ToString()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs index f3971046..0acc5a9c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -16,6 +16,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; public class AddMediaLibraryRequestMappingTests { private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); + private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() @@ -144,4 +145,45 @@ public class AddMediaLibraryRequestMappingTests Assert.NotNull(result); Assert.Null(result.CoverImage); } + + [Fact] + public void ToCommand_WhenRequestHasPathTemplateParts_ShouldMapToDtoArray() + { + // Arrange + LibraryPathTemplatePartRequest literalPart = _libraryPathTemplatePartRequestFixture.Create( + kind: nameof(LibraryPathPartKind.Literal), + representation: "Various Artists", + isOptional: false); + LibraryPathTemplatePartRequest typedPart = _libraryPathTemplatePartRequestFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}", + isOptional: true); + AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: [literalPart, typedPart]); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result.PathTemplateParts); + Assert.Equal(2, result.PathTemplateParts.Length); + Assert.Equal(literalPart.Kind, result.PathTemplateParts[0].Kind); + Assert.Equal(literalPart.Representation, result.PathTemplateParts[0].Representation); + Assert.Equal(literalPart.IsOptional, result.PathTemplateParts[0].IsOptional); + Assert.Equal(typedPart.Kind, result.PathTemplateParts[1].Kind); + Assert.Equal(typedPart.Representation, result.PathTemplateParts[1].Representation); + Assert.Equal(typedPart.IsOptional, result.PathTemplateParts[1].IsOptional); + } + + [Fact] + public void ToCommand_WhenPathTemplatePartsIsNull_ShouldMapToNull() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: null); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Null(result.PathTemplateParts); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMappingTests.cs new file mode 100644 index 00000000..7f651edd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMappingTests.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsRequestMappingTests +{ + private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapLibraryType() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "Book"); + + // Act + GetLibraryPathTemplatePartsQuery result = request.ToQuery(); + + // Assert + Assert.Equal("Book", result.LibraryType); + } + + [Theory] + [InlineData("Book")] // a written content library type + [InlineData("Movie")] // a video library type + [InlineData("Music")] // an audio library type + public void ToQuery_WhenMappingDifferentLibraryTypes_ShouldMapLibraryType(string libraryType) + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: libraryType); + + // Act + GetLibraryPathTemplatePartsQuery result = request.ToQuery(); + + // Assert + Assert.Equal(libraryType, result.LibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs index 44bf69ac..953317fe 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs @@ -3,10 +3,14 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; @@ -18,6 +22,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; public class LibraryEntityMappingTests { private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new(); [Fact] public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly() @@ -123,4 +128,126 @@ public class LibraryEntityMappingTests Assert.NotNull(result); Assert.Null(result.CoverImage); } + + [Fact] + public void ToResponse_WhenLibraryHasPathTemplateParts_ShouldOrderByPositionAndMapProperties() + { + // Arrange + LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create( + position: 2, + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: true); + LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create( + position: 0, + kind: LibraryPathPartKind.Literal, + representation: "Various Artists"); + LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create( + position: 1, + kind: LibraryPathPartKind.Separator, + representation: string.Empty); + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"], + pathTemplateParts: [firstPart, secondPart, thirdPart]); + + // Act + LibraryResponse result = entity.ToResponse(); + + // Assert + Assert.Equal(3, result.PathTemplateParts.Count); + Assert.Equal(LibraryPathPartKind.Literal.ToString(), result.PathTemplateParts[0].Kind); + Assert.Equal("Various Artists", result.PathTemplateParts[0].Representation); + Assert.False(result.PathTemplateParts[0].IsOptional); + Assert.Equal(LibraryPathPartKind.Separator.ToString(), result.PathTemplateParts[1].Kind); + Assert.Equal(string.Empty, result.PathTemplateParts[1].Representation); + Assert.False(result.PathTemplateParts[1].IsOptional); + Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.PathTemplateParts[2].Kind); + Assert.Equal("{0}", result.PathTemplateParts[2].Representation); + Assert.True(result.PathTemplateParts[2].IsOptional); + } + + [Fact] + public void ToDomainEntity_WhenLibraryHasPathTemplateParts_ShouldBuildTemplateFromOrderedParts() + { + // Arrange + LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create( + position: 1, + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: true); + LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create( + position: 0, + kind: LibraryPathPartKind.Literal, + representation: "Various Artists"); + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"], + coverImage: "D:/cover.jpg", + pathTemplateParts: [firstPart, secondPart]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(entity.Id, result.Value.Id.Value); + Assert.Equal(entity.UserId, result.Value.UserId.Value); + Assert.Equal(entity.Title, result.Value.Title); + Assert.Equal(entity.LibraryType, result.Value.LibraryType); + Assert.Equal("D:/cover.jpg", result.Value.CoverImage.Value); + Assert.Equal(2, result.Value.PathTemplate.Parts.Count); + Assert.Equal(LibraryPathPartKind.Literal, result.Value.PathTemplate.Parts[0].Kind); + Assert.Equal("Various Artists", result.Value.PathTemplate.Parts[0].Representation); + Assert.False(result.Value.PathTemplate.Parts[0].IsOptional); + Assert.Equal(LibraryPathPartKind.Artist, result.Value.PathTemplate.Parts[1].Kind); + Assert.Equal("{0}", result.Value.PathTemplate.Parts[1].Representation); + Assert.True(result.Value.PathTemplate.Parts[1].IsOptional); + } + + [Fact] + public void ToDomainEntity_WhenStoredTypedPartHasEmptyRepresentation_ShouldReturnPathTemplateLiteralCannotBeEmpty() + { + // Arrange + LibraryPathTemplatePartEntity invalidPart = _libraryPathTemplatePartEntityFixture.Create( + position: 0, + kind: LibraryPathPartKind.Artist, + representation: string.Empty); + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"], + pathTemplateParts: [invalidPart]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenStoredTypedPartHasNoPlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder() + { + // Arrange + LibraryPathTemplatePartEntity invalidPart = _libraryPathTemplatePartEntityFixture.Create( + position: 0, + kind: LibraryPathPartKind.TrackNumber, + representation: "Track"); + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"], + pathTemplateParts: [invalidPart]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs index 0a85aec0..d0827892 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs @@ -4,7 +4,9 @@ using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; @@ -21,6 +23,8 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; public class LibraryMappingTests { private readonly LibraryFixture _libraryFixture = new(); + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); [Fact] public void ToRepositoryEntity_WhenMappingValidLibrary_ShouldMapCorrectly() @@ -185,4 +189,57 @@ public class LibraryMappingTests Assert.NotNull(library.ScanIds); Assert.NotNull(result.LibraryScans); } + + [Fact] + public void ToRepositoryEntity_WhenLibraryHasPathTemplateParts_ShouldMapPartsWithSequentialPositions() + { + // Arrange + LibraryPathPart literalPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Literal, + representation: "Various Artists", + isOptional: false); + LibraryPathPart typedPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: true); + LibraryPathTemplate pathTemplate = _libraryPathTemplateFixture.Create(parts: [literalPart, typedPart]); + Library library = _libraryFixture.Create( + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"], + pathTemplate: pathTemplate); + + // Act + LibraryEntity result = library.ToRepositoryEntity(); + + // Assert + List parts = [.. result.PathTemplateParts.OrderBy(part => part.Position)]; + Assert.Equal(2, parts.Count); + Assert.Equal(0, parts[0].Position); + Assert.Equal(LibraryPathPartKind.Literal, parts[0].Kind); + Assert.Equal("Various Artists", parts[0].Representation); + Assert.False(parts[0].IsOptional); + Assert.Equal(1, parts[1].Position); + Assert.Equal(LibraryPathPartKind.Artist, parts[1].Kind); + Assert.Equal("{0}", parts[1].Representation); + Assert.True(parts[1].IsOptional); + } + + [Fact] + public void ToRepositoryEntity_WhenLibraryHasNoPathTemplateParts_ShouldMapEmptyCollection() + { + // Arrange + LibraryPathTemplate pathTemplate = _libraryPathTemplateFixture.Create(includeParts: false); + Library library = _libraryFixture.Create( + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"], + pathTemplate: pathTemplate); + + // Act + LibraryEntity result = library.ToRepositoryEntity(); + + // Assert + Assert.Empty(result.PathTemplateParts); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMappingTests.cs new file mode 100644 index 00000000..8886ae37 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMappingTests.cs @@ -0,0 +1,204 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartDtoMappingTests +{ + private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + + [Fact] + public void ToDomainParts_WhenPartsIsNull_ShouldReturnEmptyList() + { + // Act + Result> result = LibraryPathTemplatePartDtoMapping.ToDomainParts(null); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public void ToDomainParts_WhenPartsIsEmpty_ShouldReturnEmptyList() + { + // Arrange + List parts = []; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public void ToDomainParts_WhenPartsAreValid_ShouldMapKindRepresentationAndIsOptional() + { + // Arrange + LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Literal), + representation: "Various Artists", + isOptional: false); + LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}", + isOptional: true); + LibraryPathTemplatePartDto[] parts = [literalPart, typedPart]; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(LibraryPathPartKind.Literal, result.Value[0].Kind); + Assert.Equal("Various Artists", result.Value[0].Representation); + Assert.False(result.Value[0].IsOptional); + Assert.Equal(LibraryPathPartKind.Artist, result.Value[1].Kind); + Assert.Equal("{0}", result.Value[1].Representation); + Assert.True(result.Value[1].IsOptional); + } + + [Fact] + public void ToDomainParts_WhenPartIsSeparator_ShouldMapWithEmptyRepresentation() + { + // Arrange + LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Separator), + representation: @"\", + isOptional: false); + LibraryPathTemplatePartDto[] parts = [separatorPart]; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal(LibraryPathPartKind.Separator, result.Value[0].Kind); + Assert.Equal(string.Empty, result.Value[0].Representation); + Assert.False(result.Value[0].IsOptional); + } + + [Fact] + public void ToDomainParts_WhenKindIsUnknown_ShouldReturnPathTemplatePartKindNotSupportedForLibraryType() + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: "NotARealLibraryPathPartKind"); + + LibraryPathTemplatePartDto[] parts = [part]; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError); + } + + [Fact] + public void ToDomainParts_WhenKindIsNull_ShouldReturnPathTemplatePartKindNotSupportedForLibraryType() + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = null }; + + LibraryPathTemplatePartDto[] parts = [part]; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError); + } + + [Fact] + public void ToDomainParts_WhenKindUsesDifferentCasing_ShouldMapKind() + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create( + kind: "artist", + representation: "{0}", + isOptional: false); + + LibraryPathTemplatePartDto[] parts = [part]; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal(LibraryPathPartKind.Artist, result.Value[0].Kind); + Assert.Equal("{0}", result.Value[0].Representation); + Assert.False(result.Value[0].IsOptional); + } + + [Fact] + public void ToDomainParts_WhenTypedPartRepresentationIsEmpty_ShouldReturnPathTemplateLiteralCannotBeEmpty() + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: string.Empty); + + LibraryPathTemplatePartDto[] parts = [part]; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainParts_WhenTypedPartRepresentationHasNoPlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder() + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "Artist Name"); + + LibraryPathTemplatePartDto[] parts = [part]; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError); + } + + [Fact] + public void ToDomainParts_WhenTypedPartRepresentationHasDuplicatePlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder() + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0} - {0}"); + + LibraryPathTemplatePartDto[] parts = [part]; + + // Act + Result> result = parts.ToDomainParts(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs index cf7be28a..dd097183 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,6 +16,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; public class UpdateLibraryRequestMappingTests { private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); + private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() @@ -46,4 +48,45 @@ public class UpdateLibraryRequestMappingTests Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); Assert.Equal(request.ShouldSkipUnchangedDirectoriesDuringScan, result.ShouldSkipUnchangedDirectoriesDuringScan); } + + [Fact] + public void ToCommand_WhenRequestHasPathTemplateParts_ShouldMapToDtoArray() + { + // Arrange + LibraryPathTemplatePartRequest literalPart = _libraryPathTemplatePartRequestFixture.Create( + kind: nameof(LibraryPathPartKind.Literal), + representation: "Various Artists", + isOptional: false); + LibraryPathTemplatePartRequest typedPart = _libraryPathTemplatePartRequestFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}", + isOptional: true); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: [literalPart, typedPart]); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result.PathTemplateParts); + Assert.Equal(2, result.PathTemplateParts.Length); + Assert.Equal(literalPart.Kind, result.PathTemplateParts[0].Kind); + Assert.Equal(literalPart.Representation, result.PathTemplateParts[0].Representation); + Assert.Equal(literalPart.IsOptional, result.PathTemplateParts[0].IsOptional); + Assert.Equal(typedPart.Kind, result.PathTemplateParts[1].Kind); + Assert.Equal(typedPart.Representation, result.PathTemplateParts[1].Representation); + Assert.Equal(typedPart.IsOptional, result.PathTemplateParts[1].IsOptional); + } + + [Fact] + public void ToCommand_WhenPathTemplatePartsIsNull_ShouldMapToNull() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: null); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Null(result.PathTemplateParts); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMappingTests.cs index 6c82f2ca..da9a752d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMappingTests.cs @@ -21,7 +21,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class AddBookCommandMappingTests { - private readonly AddBookCommandFixture _commandBookFixture = new(); + private readonly AddBookCommandFixture _addBookCommandFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); @@ -32,7 +32,7 @@ public class AddBookCommandMappingTests { // Arrange Guid libraryId = Guid.NewGuid(); - AddBookCommand command = _commandBookFixture.Create(libraryId: libraryId.ToString()); + AddBookCommand command = _addBookCommandFixture.Create(libraryId: libraryId.ToString()); // Act Result result = command.ToDomainEntity(libraryId); @@ -57,7 +57,7 @@ public class AddBookCommandMappingTests { // Arrange Guid libraryId = Guid.NewGuid(); - AddBookCommand command = _commandBookFixture.Create( + AddBookCommand command = _addBookCommandFixture.Create( libraryId: libraryId.ToString(), isbns: [], contributors: [], @@ -103,7 +103,7 @@ public class AddBookCommandMappingTests public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() { // Arrange - AddBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); + AddBookCommand command = _addBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); // Act Result result = command.ToDomainEntity(Guid.NewGuid()); @@ -117,7 +117,7 @@ public class AddBookCommandMappingTests public void ToDomainEntity_WhenIsbnCreationFails_ShouldReturnError() { // Arrange - AddBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + AddBookCommand command = _addBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); // Act Result result = command.ToDomainEntity(Guid.NewGuid()); @@ -131,7 +131,7 @@ public class AddBookCommandMappingTests public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() { // Arrange - AddBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); + AddBookCommand command = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); // Act Result result = command.ToDomainEntity(Guid.NewGuid()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs index 09d0264e..83d5290f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; @@ -19,7 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class AddBookRequestMappingTests { - private readonly AddBookRequestFixture _requestFixture = new(); + private readonly AddBookRequestFixture _addBookRequestFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -28,7 +28,7 @@ public class AddBookRequestMappingTests { // Arrange Guid libraryId = Guid.NewGuid(); - AddBookRequest request = _requestFixture.Create(); + AddBookRequest request = _addBookRequestFixture.Create(); // Act AddBookCommand result = request.ToCommand(libraryId.ToString()); @@ -61,7 +61,7 @@ public class AddBookRequestMappingTests { // Arrange Guid libraryId = Guid.NewGuid(); - AddBookRequest request = _requestFixture.Create( + AddBookRequest request = _addBookRequestFixture.Create( path: "/books/test.epub", metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"), includeFormat: false, @@ -110,7 +110,7 @@ public class AddBookRequestMappingTests { // Arrange Guid libraryId = Guid.NewGuid(); - AddBookRequest request = _requestFixture.Create( + AddBookRequest request = _addBookRequestFixture.Create( path: "/books/test.epub", metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"), isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs index 40e5383a..d94307bc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs @@ -25,6 +25,9 @@ public class BookMetadataDtoMappingTests private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); [Fact] public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItToTheBook() @@ -126,7 +129,7 @@ public class BookMetadataDtoMappingTests Book book = _bookFixture.Create(); BookMetadataDto metadata = _bookMetadataDtoFixture.Create( title: "A valid title", - tags: [new TagDto(" ")]); + tags: [_tagDtoFixture.Create(name: " ")]); // Act Result result = book.ApplyMetadata(metadata); @@ -142,7 +145,7 @@ public class BookMetadataDtoMappingTests Book book = _bookFixture.Create(); BookMetadataDto metadata = _bookMetadataDtoFixture.Create( title: "A valid title", - isbns: [new IsbnDto("not-an-isbn", IsbnFormat.Isbn13)]); + isbns: [_isbnDtoFixture.Create(value: "not-an-isbn", format: IsbnFormat.Isbn13)]); // Act Result result = book.ApplyMetadata(metadata); @@ -158,7 +161,7 @@ public class BookMetadataDtoMappingTests Book book = _bookFixture.Create(); BookMetadataDto metadata = _bookMetadataDtoFixture.Create( title: "A valid title", - ratings: [new BookRatingDto(-1m, 5m, null, null)]); + ratings: [_bookRatingDtoFixture.Create(value: -1m, maxValue: 5m, includeSource: false, includeVoteCount: false)]); // Act Result result = book.ApplyMetadata(metadata); @@ -196,8 +199,8 @@ public class BookMetadataDtoMappingTests Book book = _bookFixture.Create(); BookMetadataDto metadata = _bookMetadataDtoFixture.Create( title: "A valid title", - isbns: [new IsbnDto("9780306406157", IsbnFormat.Isbn13)], - ratings: [new BookRatingDto(4m, 5m, null, 10)]); + isbns: [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)], + ratings: [_bookRatingDtoFixture.Create(value: 4m, maxValue: 5m, voteCount: 10, includeSource: false)]); // Act Result result = book.ApplyMetadata(metadata); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs index c89839e2..48a95a2d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMappingTests.cs @@ -23,7 +23,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class UpdateBookCommandMappingTests { - private readonly UpdateBookCommandFixture _commandBookFixture = new(); + private readonly UpdateBookCommandFixture _updateBookCommandFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); @@ -36,7 +36,7 @@ public class UpdateBookCommandMappingTests // Arrange Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookCommand command = _commandBookFixture.Create(libraryId: libraryId.ToString(), bookId: bookId.ToString()); + UpdateBookCommand command = _updateBookCommandFixture.Create(libraryId: libraryId.ToString(), bookId: bookId.ToString()); BookEntity existingBook = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: "/books/the-book.epub"); DateTime createdOnUtc = existingBook.CreatedOnUtc; @@ -66,7 +66,7 @@ public class UpdateBookCommandMappingTests // Arrange Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookCommand command = _commandBookFixture.Create( + UpdateBookCommand command = _updateBookCommandFixture.Create( libraryId: libraryId.ToString(), bookId: bookId.ToString(), isbns: [], @@ -115,7 +115,7 @@ public class UpdateBookCommandMappingTests public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); + UpdateBookCommand command = _updateBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); BookEntity existingBook = _bookEntityFixture.Create(); // Act @@ -130,7 +130,7 @@ public class UpdateBookCommandMappingTests public void ToDomainEntity_WhenIsbnCreationFails_ShouldReturnError() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + UpdateBookCommand command = _updateBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); BookEntity existingBook = _bookEntityFixture.Create(); // Act @@ -145,7 +145,7 @@ public class UpdateBookCommandMappingTests public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); + UpdateBookCommand command = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); BookEntity existingBook = _bookEntityFixture.Create(); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMappingTests.cs index 9d47b1c4..b04069d2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMappingTests.cs @@ -18,7 +18,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class UpdateBookCoverCommandMappingTests { - private readonly UpdateBookCoverCommandFixture _commandFixture = new(); + private readonly UpdateBookCoverCommandFixture _updateBookCoverCommandFixture = new(); private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); [Fact] @@ -27,7 +27,7 @@ public class UpdateBookCoverCommandMappingTests // Arrange Guid userId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookCoverCommand command = _commandFixture.Create(bookId: bookId.ToString()); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: bookId.ToString()); string storedCoverPath = "/media/books/cover.jpg"; // Act @@ -50,7 +50,7 @@ public class UpdateBookCoverCommandMappingTests // Arrange Guid userId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookCoverCommand command = _commandFixture.Create(bookId: bookId.ToString()); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: bookId.ToString()); BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg", status: ArtworkStatus.Pending); string storedCoverPath = "/media/books/cover.jpg"; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs index 0b3a9bf8..5f954be7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMappingTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; @@ -18,7 +18,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class UpdateBookRequestMappingTests { - private readonly UpdateBookRequestFixture _requestFixture = new(); + private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); [Fact] @@ -27,7 +27,7 @@ public class UpdateBookRequestMappingTests // Arrange Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _requestFixture.Create(); + UpdateBookRequest request = _updateBookRequestFixture.Create(); // Act UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString()); @@ -61,7 +61,7 @@ public class UpdateBookRequestMappingTests // Arrange Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _requestFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookRequest request = _updateBookRequestFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString()); @@ -95,7 +95,7 @@ public class UpdateBookRequestMappingTests // Arrange Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _requestFixture.Create( + UpdateBookRequest request = _updateBookRequestFixture.Create( isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], contributors: [ @@ -130,7 +130,7 @@ public class UpdateBookRequestMappingTests public void ToCommand_WhenRouteValuesAreNotParseable_ShouldMapThemAsIs() { // Arrange - UpdateBookRequest request = _requestFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookRequest request = _updateBookRequestFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act UpdateBookCommand result = request.ToCommand("not-a-library-guid", "not-a-guid"); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs index d859ed13..8126c123 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs @@ -21,13 +21,13 @@ public class BookRatingDtoMappingTests private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingCompleteBookRatinDto_ShouldMapAllPropertiesCorrectly() + public void ToDomainValueObject_WhenMappingCompleteBookRatinDto_ShouldMapAllPropertiesCorrectly() { // Arrange BookRatingDto dto = _bookRatingDtoFixture.Create(); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -53,13 +53,13 @@ public class BookRatingDtoMappingTests } [Fact] - public void ToDomainEntity_WhenMappingMinimalBookRatingDto_ShouldMapRequiredPropertiesCorrectly() + public void ToDomainValueObject_WhenMappingMinimalBookRatingDto_ShouldMapRequiredPropertiesCorrectly() { // Arrange BookRatingDto dto = _bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -71,13 +71,13 @@ public class BookRatingDtoMappingTests } [Fact] - public void ToDomainEntity_WhenMappingInvalidBookRatingDto_ShouldReturnError() + public void ToDomainValueObject_WhenMappingInvalidBookRatingDto_ShouldReturnError() { // Arrange BookRatingDto dto = _bookRatingDtoFixture.Create(value: 10, maxValue: 5); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -94,7 +94,7 @@ public class BookRatingDtoMappingTests ]; // Act - IEnumerable> results = dtos.ToDomainEntities(); + IEnumerable> results = dtos.ToDomainValueObjects(); // Assert Assert.NotNull(results); @@ -129,7 +129,7 @@ public class BookRatingDtoMappingTests ]; // Act - IEnumerable> results = dtos.ToDomainEntities(); + IEnumerable> results = dtos.ToDomainValueObjects(); // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs index 465a89eb..b7db8498 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs @@ -19,13 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class BookRatingEntityMappingTests { - private readonly BookRatingEntityFixture _fixture = new(); + private readonly BookRatingEntityFixture _bookRatingEntityFixture = new(); [Fact] public void ToResponse_WhenMappingValidBookRatingEntity_ShouldMapCorrectly() { // Arrange - BookRatingEntity entity = _fixture.Create(); + BookRatingEntity entity = _bookRatingEntityFixture.Create(); // Act BookRatingDto result = entity.ToResponse(); @@ -42,7 +42,7 @@ public class BookRatingEntityMappingTests public void ToResponse_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults() { // Arrange - BookRatingEntity entity = _fixture.Create(includeValues: false); + BookRatingEntity entity = _bookRatingEntityFixture.Create(includeValues: false); // Act BookRatingDto result = entity.ToResponse(); @@ -59,7 +59,7 @@ public class BookRatingEntityMappingTests public void ToResponses_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly() { // Arrange - List entities = _fixture.CreateMany(2); + List entities = _bookRatingEntityFixture.CreateMany(2); // Act IEnumerable results = entities.ToResponses(); @@ -76,13 +76,13 @@ public class BookRatingEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingValidBookRatingEntity_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidBookRatingEntity_ShouldMapCorrectly() { // Arrange - BookRatingEntity entity = _fixture.Create(); + BookRatingEntity entity = _bookRatingEntityFixture.Create(); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -94,13 +94,13 @@ public class BookRatingEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults() + public void ToDomainValueObject_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults() { // Arrange - BookRatingEntity entity = _fixture.Create(includeValues: false); + BookRatingEntity entity = _bookRatingEntityFixture.Create(includeValues: false); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -112,13 +112,13 @@ public class BookRatingEntityMappingTests } [Fact] - public void ToDomainEntities_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly() { // Arrange - List entities = _fixture.CreateMany(2); + List entities = _bookRatingEntityFixture.CreateMany(2); // Act - IEnumerable> results = entities.ToDomainEntities(); + IEnumerable> results = entities.ToDomainValueObjects(); // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs index 96b6737d..9855a514 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs @@ -22,13 +22,13 @@ public class IsbnDtoMappingTests private readonly IsbnDtoFixture _isbnDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingValidIsbn10Dto_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidIsbn10Dto_ShouldMapCorrectly() { // Arrange IsbnDto dto = _isbnDtoFixture.Create(format: IsbnFormat.Isbn10); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -38,13 +38,13 @@ public class IsbnDtoMappingTests } [Fact] - public void ToDomainEntity_WhenMappingValidIsbn13Dto_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidIsbn13Dto_ShouldMapCorrectly() { // Arrange IsbnDto dto = _isbnDtoFixture.Create(format: IsbnFormat.Isbn13); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -54,13 +54,13 @@ public class IsbnDtoMappingTests } [Fact] - public void ToDomainEntity_WhenMappingDtoWithoutFormat_ShouldUseDefaultFormat() + public void ToDomainValueObject_WhenMappingDtoWithoutFormat_ShouldUseDefaultFormat() { // Arrange IsbnDto dto = _isbnDtoFixture.Create(); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -70,13 +70,13 @@ public class IsbnDtoMappingTests } [Fact] - public void ToDomainEntity_WhenMappingInvalidIsbnDto_ShouldReturnError() + public void ToDomainValueObject_WhenMappingInvalidIsbnDto_ShouldReturnError() { // Arrange IsbnDto dto = _isbnDtoFixture.Create("invalid-isbn", IsbnFormat.Isbn13); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); @@ -94,7 +94,7 @@ public class IsbnDtoMappingTests ]; // Act - IEnumerable> results = dtos.ToDomainEntities(); + IEnumerable> results = dtos.ToDomainValueObjects(); // Assert Assert.NotNull(results); @@ -125,7 +125,7 @@ public class IsbnDtoMappingTests ]; // Act - IEnumerable> results = dtos.ToDomainEntities(); + IEnumerable> results = dtos.ToDomainValueObjects(); // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs index 37c28ee3..98161fb8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs @@ -61,7 +61,7 @@ public class IsbnEntityMappingTests public void ToResponse_WhenMappingInvalidIsbnEntity_ShouldPreserveValues(string? value, IsbnFormat? format) { // Arrange - IsbnEntity entity = _isbnEntityFixture.Create(value: value, format: format, includeValue: value is not null); + IsbnEntity entity = _isbnEntityFixture.Create(value: value, format: format, includeValue: value is not null, includeFormat: false); // Act IsbnDto result = entity.ToResponse(); @@ -72,13 +72,13 @@ public class IsbnEntityMappingTests } [Fact] - public void ToDomainEntity_WhenMappingValidIsbnEntity_ShouldMapCorrectly() + public void ToDomainValueObject_WhenMappingValidIsbnEntity_ShouldMapCorrectly() { // Arrange IsbnEntity entity = _isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -91,20 +91,20 @@ public class IsbnEntityMappingTests [InlineData("")] [InlineData(" ")] [InlineData(null)] - public void ToDomainEntity_WhenMappingInvalidIsbnEntity_ShouldReturnError(string? invalidValue) + public void ToDomainValueObject_WhenMappingInvalidIsbnEntity_ShouldReturnError(string? invalidValue) { // Arrange IsbnEntity entity = _isbnEntityFixture.Create(value: invalidValue, includeValue: invalidValue is not null); // Act - Result result = entity.ToDomainEntity(); + Result result = entity.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); } [Fact] - public void ToDomainEntities_WhenMappingMultipleValidIsbnEntities_ShouldMapAllCorrectly() + public void ToDomainValueObjects_WhenMappingMultipleValidIsbnEntities_ShouldMapAllCorrectly() { // Arrange List entities = @@ -114,7 +114,7 @@ public class IsbnEntityMappingTests ]; // Act - IEnumerable> results = entities.ToDomainEntities(); + IEnumerable> results = entities.ToDomainValueObjects(); // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMappingTests.cs index 10def379..0fcecf71 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMappingTests.cs @@ -23,13 +23,13 @@ public class WrittenContentMetadataDtoMappingTests private readonly TagDtoFixture _tagDtoFixture = new(); [Fact] - public void ToDomainEntity_WhenMappingCompleteWrittenContentMetadataDto_ShouldMapAllPropertiesCorrectly() + public void ToDomainValueObject_WhenMappingCompleteWrittenContentMetadataDto_ShouldMapAllPropertiesCorrectly() { // Arrange WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -51,7 +51,7 @@ public class WrittenContentMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenOptionalValuesAreMissing_ShouldMapWithoutOptionalValues() + public void ToDomainValueObject_WhenOptionalValuesAreMissing_ShouldMapWithoutOptionalValues() { // Arrange WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create( @@ -63,7 +63,7 @@ public class WrittenContentMetadataDtoMappingTests includePageCount: false); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.False(result.IsFailure); @@ -76,7 +76,7 @@ public class WrittenContentMetadataDtoMappingTests } [Fact] - public void ToDomainEntity_WhenReleaseInfoCreationFails_ShouldReturnError() + public void ToDomainValueObject_WhenReleaseInfoCreationFails_ShouldReturnError() { // Arrange WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create( @@ -85,33 +85,33 @@ public class WrittenContentMetadataDtoMappingTests originalReleaseYear: 2024)); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); } [Fact] - public void ToDomainEntity_WhenGenreCreationFails_ShouldReturnError() + public void ToDomainValueObject_WhenGenreCreationFails_ShouldReturnError() { // Arrange WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); } [Fact] - public void ToDomainEntity_WhenTagCreationFails_ShouldReturnError() + public void ToDomainValueObject_WhenTagCreationFails_ShouldReturnError() { // Arrange WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")]); // Act - Result result = dto.ToDomainEntity(); + Result result = dto.ToDomainValueObject(); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryBookReadersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryBookReadersRequestMappingTests.cs index 3ad995c5..c14161c0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryBookReadersRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryBookReadersRequestMappingTests.cs @@ -14,13 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class GetLibraryBookReadersRequestMappingTests { - private readonly GetLibraryBookReadersRequestFixture _requestFixture = new(); + private readonly GetLibraryBookReadersRequestFixture _getLibraryBookReadersRequestFixture = new(); [Fact] public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - GetLibraryBookReadersRequest request = _requestFixture.Create(); + GetLibraryBookReadersRequest request = _getLibraryBookReadersRequestFixture.Create(); // Act GetLibraryBookReadersQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMappingTests.cs index 109eeb7c..ada07090 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using System; using System.Diagnostics.CodeAnalysis; @@ -14,11 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class GetLibraryMetadataProvidersRequestMappingTests { + private readonly GetLibraryMetadataProvidersRequestFixture _getLibraryMetadataProvidersRequestFixture = new(); + [Fact] public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - GetLibraryMetadataProvidersRequest request = new(LibraryId: Guid.NewGuid()); + GetLibraryMetadataProvidersRequest request = _getLibraryMetadataProvidersRequestFixture.Create(Guid.NewGuid()); // Act GetLibraryMetadataProvidersQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetPluginSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetPluginSettingsRequestMappingTests.cs index 5cdbaef3..8c930d22 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetPluginSettingsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetPluginSettingsRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using System; using System.Diagnostics.CodeAnalysis; @@ -14,11 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class GetPluginSettingsRequestMappingTests { + private readonly GetPluginSettingsRequestFixture _getPluginSettingsRequestFixture = new(); + [Fact] public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - GetPluginSettingsRequest request = new(PluginId: Guid.NewGuid()); + GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(Guid.NewGuid()); // Act GetPluginSettingsQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryBookReaderConfigurationEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryBookReaderConfigurationEntityMappingTests.cs index 98afdca6..7cd62167 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryBookReaderConfigurationEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryBookReaderConfigurationEntityMappingTests.cs @@ -16,14 +16,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class LibraryBookReaderConfigurationEntityMappingTests { - private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); [Fact] public void ToResponse_WhenMappingValidConfiguration_ShouldMapCorrectly() { // Arrange Guid pluginId = Guid.NewGuid(); - LibraryBookReaderConfigurationEntity configuration = _configurationEntityFixture.Create(pluginId: pluginId, isEnabled: false); + LibraryBookReaderConfigurationEntity configuration = _libraryBookReaderConfigurationEntityFixture.Create(pluginId: pluginId, isEnabled: false); IReadOnlyList supportedExtensions = [".epub", ".pdf"]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMappingTests.cs index c2e4f3a5..4b5537ac 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMappingTests.cs @@ -15,7 +15,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class LibraryMetadataProviderConfigurationEntityMappingTests { - private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); [Fact] public void ToResponse_WhenMappingValidConfiguration_ShouldMapCorrectly() @@ -23,7 +23,7 @@ public class LibraryMetadataProviderConfigurationEntityMappingTests // Arrange Guid libraryId = Guid.NewGuid(); Guid pluginId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity configuration = _configurationEntityFixture.Create(libraryId, pluginId, 3); + LibraryMetadataProviderConfigurationEntity configuration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, 3); // Act LibraryMetadataProviderResponse result = configuration.ToResponse("My Provider"); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginSettingDescriptorMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginSettingDescriptorMappingTests.cs index a3a5fee7..2e4f008d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginSettingDescriptorMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginSettingDescriptorMappingTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Fixtures.Common.Models.DTO.Settings; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,11 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class PluginSettingDescriptorMappingTests { + private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new(); + [Fact] public void ToResponse_WhenMappingValidDescriptor_ShouldMapCorrectly() { // Arrange - PluginSettingDescriptorDto descriptor = new("apiKey", "API Key", PluginSettingType.Text, "default", null); + PluginSettingDescriptorDto descriptor = _pluginSettingDescriptorDtoFixture.Create("apiKey", "API Key", PluginSettingType.Text, "default", null); // Act PluginSettingDescriptorResponse result = descriptor.ToResponse(); @@ -41,7 +44,7 @@ public class PluginSettingDescriptorMappingTests public void ToResponse_WhenMappingDifferentSettingTypes_ShouldMapTypeCorrectly(PluginSettingType type) { // Arrange - PluginSettingDescriptorDto descriptor = new("key", "Label", type, null, null); + PluginSettingDescriptorDto descriptor = _pluginSettingDescriptorDtoFixture.Create("key", "Label", type, null, null); // Act PluginSettingDescriptorResponse result = descriptor.ToResponse(); @@ -54,7 +57,7 @@ public class PluginSettingDescriptorMappingTests public void ToResponse_WhenMappingDescriptorWithAllowedValues_ShouldMapAllowedValues() { // Arrange - PluginSettingDescriptorDto descriptor = new("mode", "Mode", PluginSettingType.Select, null, ["fast", "slow"]); + PluginSettingDescriptorDto descriptor = _pluginSettingDescriptorDtoFixture.Create("mode", "Mode", PluginSettingType.Select, null, ["fast", "slow"]); // Act PluginSettingDescriptorResponse result = descriptor.ToResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs index 6a56ddcd..d88564a1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using System; using System.Collections.Generic; @@ -15,11 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class ReorderLibraryMetadataProvidersRequestMappingTests { + private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - ReorderLibraryMetadataProvidersRequest request = new(LibraryId: Guid.NewGuid(), PluginIds: [Guid.NewGuid(), Guid.NewGuid()]); + ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(Guid.NewGuid(), [Guid.NewGuid(), Guid.NewGuid()]); // Act ReorderLibraryMetadataProvidersCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs index c9c7f23b..cec75047 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs @@ -14,13 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class SetLibraryBookReaderEnabledRequestMappingTests { - private readonly SetLibraryBookReaderEnabledRequestFixture _requestFixture = new(); + private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - SetLibraryBookReaderEnabledRequest request = _requestFixture.Create(); + SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); // Act SetLibraryBookReaderEnabledCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs index 474efa4e..26376d27 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using System; using System.Diagnostics.CodeAnalysis; @@ -14,11 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class SetLibraryMetadataProviderEnabledRequestMappingTests { + private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - SetLibraryMetadataProviderEnabledRequest request = new(LibraryId: Guid.NewGuid(), PluginId: Guid.NewGuid(), IsEnabled: true); + SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(Guid.NewGuid(), Guid.NewGuid(), true); // Act SetLibraryMetadataProviderEnabledCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/UpdatePluginSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/UpdatePluginSettingsRequestMappingTests.cs index 1c08cf99..91dd89ed 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/UpdatePluginSettingsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/UpdatePluginSettingsRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Plugins; using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using System; using System.Collections.Generic; @@ -15,11 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; [ExcludeFromCodeCoverage] public class UpdatePluginSettingsRequestMappingTests { + private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - UpdatePluginSettingsRequest request = new(PluginId: Guid.NewGuid(), Settings: new Dictionary { ["key"] = "value" }); + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(Guid.NewGuid(), new Dictionary { ["key"] = "value" }); // Act UpdatePluginSettingsCommand result = request.ToCommand(); @@ -34,7 +37,7 @@ public class UpdatePluginSettingsRequestMappingTests public void ToCommand_WhenMappingRequestWithNullSettings_ShouldMapNullSettings() { // Arrange - UpdatePluginSettingsRequest request = new(PluginId: Guid.NewGuid(), Settings: null); + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(Guid.NewGuid(), includeSettings: false); // Act UpdatePluginSettingsCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/AddScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/AddScheduledJobRequestMappingTests.cs index 4180f78b..6202c339 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/AddScheduledJobRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/AddScheduledJobRequestMappingTests.cs @@ -15,13 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; [ExcludeFromCodeCoverage] public class AddScheduledJobRequestMappingTests { - private readonly AddScheduledJobRequestFixture _requestFixture = new(); + private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - AddScheduledJobRequest request = _requestFixture.Create( + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create( name: "Scan at 6am", taskType: ScheduledTaskType.ScanMediaLibraries, scheduleType: ScheduleType.DailyAtHourAndMinute, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/FireScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/FireScheduledJobRequestMappingTests.cs index d8cda581..d6d5980f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/FireScheduledJobRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/FireScheduledJobRequestMappingTests.cs @@ -15,14 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; [ExcludeFromCodeCoverage] public class FireScheduledJobRequestMappingTests { - private readonly FireScheduledJobRequestFixture _requestFixture = new(); + private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid scheduledJobId = Guid.NewGuid(); - FireScheduledJobRequest request = _requestFixture.Create(scheduledJobId); + FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(scheduledJobId); // Act FireScheduledJobCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMappingTests.cs index f6be56d1..35d19654 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMappingTests.cs @@ -15,7 +15,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; [ExcludeFromCodeCoverage] public class GetScheduledJobHistoryRequestMappingTests { - private readonly GetScheduledJobHistoryRequestFixture _requestFixture = new(); + private readonly GetScheduledJobHistoryRequestFixture _getScheduledJobHistoryRequestFixture = new(); [Fact] public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() @@ -23,7 +23,7 @@ public class GetScheduledJobHistoryRequestMappingTests // Arrange DateTime from = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime to = new(2026, 1, 2, 0, 0, 0, DateTimeKind.Utc); - GetScheduledJobHistoryRequest request = _requestFixture.Create(from, to); + GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(from, to); // Act GetScheduledJobHistoryQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/RemoveScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/RemoveScheduledJobRequestMappingTests.cs index 1afa775e..53c5e0d2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/RemoveScheduledJobRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/RemoveScheduledJobRequestMappingTests.cs @@ -15,14 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; [ExcludeFromCodeCoverage] public class RemoveScheduledJobRequestMappingTests { - private readonly RemoveScheduledJobRequestFixture _requestFixture = new(); + private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid scheduledJobId = Guid.NewGuid(); - RemoveScheduledJobRequest request = _requestFixture.Create(scheduledJobId); + RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(scheduledJobId); // Act RemoveScheduledJobCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StartScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StartScheduledJobRequestMappingTests.cs index 374c6a6b..e990b0be 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StartScheduledJobRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StartScheduledJobRequestMappingTests.cs @@ -15,14 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; [ExcludeFromCodeCoverage] public class StartScheduledJobRequestMappingTests { - private readonly StartScheduledJobRequestFixture _requestFixture = new(); + private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid scheduledJobId = Guid.NewGuid(); - StartScheduledJobRequest request = _requestFixture.Create(scheduledJobId); + StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(scheduledJobId); // Act StartScheduledJobCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StopScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StopScheduledJobRequestMappingTests.cs index d67d254f..88d72564 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StopScheduledJobRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StopScheduledJobRequestMappingTests.cs @@ -15,14 +15,14 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; [ExcludeFromCodeCoverage] public class StopScheduledJobRequestMappingTests { - private readonly StopScheduledJobRequestFixture _requestFixture = new(); + private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange Guid scheduledJobId = Guid.NewGuid(); - StopScheduledJobRequest request = _requestFixture.Create(scheduledJobId); + StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(scheduledJobId); // Act StopScheduledJobCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMappingTests.cs index 3b09a096..94501c93 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMappingTests.cs @@ -15,13 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; [ExcludeFromCodeCoverage] public class UpdateSchedulerDisplayPreferencesRequestMappingTests { - private readonly UpdateSchedulerDisplayPreferencesRequestFixture _requestFixture = new(); + private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - UpdateSchedulerDisplayPreferencesRequest request = _requestFixture.Create( + UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create( jobTypeFilter: ScheduledTaskType.CleanTemporaryFiles, displayTimeSpan: 15, displayTimeUnit: SchedulerDisplayTimeUnit.Hours); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs index 6dcb16ce..66294113 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs @@ -39,7 +39,7 @@ public class DeleteThemeRequestMappingTests public void ToCommand_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId) { // Arrange - DeleteThemeRequest request = new(themeId); + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(themeId); // Act DeleteThemeCommand result = request.ToCommand(); @@ -53,7 +53,7 @@ public class DeleteThemeRequestMappingTests public void ToCommand_WhenThemeIdIsNull_ShouldMapNull() { // Arrange - DeleteThemeRequest request = new(null); + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(includeThemeId: false); // Act DeleteThemeCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs index 8c758111..ee88301c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs @@ -39,7 +39,7 @@ public class GetThemeArchiveRequestMappingTests public void ToQuery_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId) { // Arrange - GetThemeArchiveRequest request = new(themeId); + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(themeId); // Act GetThemeArchiveQuery result = request.ToQuery(); @@ -53,7 +53,7 @@ public class GetThemeArchiveRequestMappingTests public void ToQuery_WhenThemeIdIsNull_ShouldMapNull() { // Arrange - GetThemeArchiveRequest request = new(null); + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(includeThemeId: false); // Act GetThemeArchiveQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs index d6775a90..a5e9b0f3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs @@ -40,7 +40,7 @@ public class GetThemeAssetRequestMappingTests public void ToQuery_WhenMappingDifferentThemeIdsAndAssetPaths_ShouldMapCorrectly(string themeId, string assetPath) { // Arrange - GetThemeAssetRequest request = new(themeId, assetPath); + GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(themeId, assetPath); // Act GetThemeAssetQuery result = request.ToQuery(); @@ -55,7 +55,7 @@ public class GetThemeAssetRequestMappingTests public void ToQuery_WhenFieldsAreNull_ShouldMapNull() { // Arrange - GetThemeAssetRequest request = new(null, null); + GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(includeThemeId: false, includeAssetPath: false); // Act GetThemeAssetQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs index ff5f7043..a59ee9b2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs @@ -40,7 +40,7 @@ public class GetThemeTemplateRequestMappingTests public void ToQuery_WhenMappingDifferentThemeIdsAndPageKeys_ShouldMapCorrectly(string themeId, string pageKey) { // Arrange - GetThemeTemplateRequest request = new(themeId, pageKey); + GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(themeId, pageKey); // Act GetThemeTemplateQuery result = request.ToQuery(); @@ -55,7 +55,7 @@ public class GetThemeTemplateRequestMappingTests public void ToQuery_WhenFieldsAreNull_ShouldMapNull() { // Arrange - GetThemeTemplateRequest request = new(null, null); + GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(includeThemeId: false, includePageKey: false); // Act GetThemeTemplateQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs index cdde81c5..639382c8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs @@ -39,7 +39,7 @@ public class SetCurrentThemeRequestMappingTests public void ToCommand_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId) { // Arrange - SetCurrentThemeRequest request = new(themeId); + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(themeId); // Act SetCurrentThemeCommand result = request.ToCommand(); @@ -53,7 +53,7 @@ public class SetCurrentThemeRequestMappingTests public void ToCommand_WhenThemeIdIsNull_ShouldMapNull() { // Arrange - SetCurrentThemeRequest request = new(null); + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(includeThemeId: false); // Act SetCurrentThemeCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs index 426f561b..2ae1fa52 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs @@ -14,13 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users; [ExcludeFromCodeCoverage] public class UpdateUserSettingsRequestMappingTests { - private readonly UpdateUserSettingsRequestFixture _requestFixture = new(); + private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new(); [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - UpdateUserSettingsRequest request = _requestFixture.Create( + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs index fbaa8787..498d18e2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs @@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Admin.Authorization.Permissions.Queries.GetPermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -38,6 +39,7 @@ public class GetPermissionsQueryHandlerTests private readonly Guid _userId; private readonly GetPermissionsQueryFixture _getPermissionsQueryFixture = new(); private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -74,7 +76,7 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = permissions, CurrentPage = 1, PerPage = permissions.Count, Count = permissions.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: permissions, currentPage: 1, perPage: permissions.Count, count: permissions.Count, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -158,7 +160,7 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = permissions, CurrentPage = 1, PerPage = permissions.Count, Count = permissions.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: permissions, currentPage: 1, perPage: permissions.Count, count: permissions.Count, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, cancellationToken); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs index 9ed9e01c..a3061faf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs @@ -18,13 +18,13 @@ namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.A public class AddRoleCommandValidatorTests { private readonly AddRoleCommandValidator _validator = new(); - private readonly AddRoleCommandFixture _fixture = new(); + private readonly AddRoleCommandFixture _addRoleCommandFixture = new(); [Fact] public void Validate_WhenRoleNameIsNull_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.Create(); + AddRoleCommand command = _addRoleCommandFixture.Create(); command = command with { RoleName = null! }; // Act @@ -38,7 +38,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenRoleNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.Create(); + AddRoleCommand command = _addRoleCommandFixture.Create(); command = command with { RoleName = string.Empty }; // Act @@ -52,7 +52,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenRoleNameIsWhitespace_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.Create(); + AddRoleCommand command = _addRoleCommandFixture.Create(); command = command with { RoleName = " " }; // Act @@ -66,7 +66,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenPermissionsIsNull_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.Create(); + AddRoleCommand command = _addRoleCommandFixture.Create(); command = command with { Permissions = null! }; // Act @@ -80,7 +80,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenPermissionsIsEmpty_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.Create(); + AddRoleCommand command = _addRoleCommandFixture.Create(); command = command with { Permissions = [] }; // Act @@ -94,7 +94,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenPermissionContainsEmptyGuid_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.Create(); + AddRoleCommand command = _addRoleCommandFixture.Create(); command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] }; // Act @@ -108,7 +108,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.Create(); + AddRoleCommand command = _addRoleCommandFixture.Create(); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs index 2869e5be..1accb6a0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Primitives; using System; @@ -17,12 +18,13 @@ namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.D public class DeleteRoleCommandValidatorTests { private readonly DeleteRoleCommandValidator _validator = new(); + private readonly DeleteRoleCommandFixture _deleteRoleCommandFixture = new(); [Fact] public void Validate_WhenRoleIdIsEmpty_ShouldHaveValidationError() { // Arrange - DeleteRoleCommand command = new(Guid.Empty); + DeleteRoleCommand command = _deleteRoleCommandFixture.Create(Guid.Empty); // Act List result = _validator.TestValidate(command); @@ -35,7 +37,7 @@ public class DeleteRoleCommandValidatorTests public void Validate_WhenRoleIdIsValid_ShouldNotHaveValidationError() { // Arrange - DeleteRoleCommand command = new(Guid.NewGuid()); + DeleteRoleCommand command = _deleteRoleCommandFixture.Create(Guid.NewGuid()); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs index 4a0554f6..469e02ff 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs @@ -18,13 +18,13 @@ namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.U public class UpdateRoleCommandValidatorTests { private readonly UpdateRoleCommandValidator _validator = new(); - private readonly UpdateRoleCommandFixture _fixture = new(); + private readonly UpdateRoleCommandFixture _updateRoleCommandFixture = new(); [Fact] public void Validate_WhenRoleIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.Create(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); command = command with { RoleId = Guid.Empty }; // Act @@ -38,7 +38,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenRoleNameIsNull_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.Create(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); command = command with { RoleName = null! }; // Act @@ -52,7 +52,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenRoleNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.Create(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); command = command with { RoleName = string.Empty }; // Act @@ -66,7 +66,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenRoleNameIsWhitespace_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.Create(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); command = command with { RoleName = " " }; // Act @@ -80,7 +80,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenPermissionsIsNull_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.Create(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); command = command with { Permissions = null! }; // Act @@ -94,7 +94,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenPermissionsIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.Create(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); command = command with { Permissions = [] }; // Act @@ -108,7 +108,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenPermissionContainsEmptyGuid_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.Create(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] }; // Act @@ -122,7 +122,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.Create(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs index 8a3595e0..d46bed55 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Primitives; using System; @@ -17,12 +18,13 @@ namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.Ge public class GetRolePermissionsQueryValidatorTests { private readonly GetRolePermissionsQueryValidator _validator = new(); + private readonly GetRolePermissionsQueryFixture _getRolePermissionsQueryFixture = new(); [Fact] public void Validate_WhenRoleIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetRolePermissionsQuery query = new(Guid.Empty); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(Guid.Empty); // Act List result = _validator.TestValidate(query); @@ -35,7 +37,7 @@ public class GetRolePermissionsQueryValidatorTests public void Validate_WhenRoleIdIsValid_ShouldNotHaveValidationError() { // Arrange - GetRolePermissionsQuery query = new(Guid.NewGuid()); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(Guid.NewGuid()); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs index 7569ad9f..4e1b5eb8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs @@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -35,6 +36,7 @@ public class GetRolesQueryHandlerTests private readonly GetRolesQueryHandler _sut; private readonly GetRolesQueryFixture _getRolesQueryFixture = new(); private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly Guid _userId; /// @@ -126,7 +128,7 @@ public class GetRolesQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockRoleRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = roles, CurrentPage = 1, PerPage = roles.Count, Count = roles.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: roles, currentPage: 1, perPage: roles.Count, count: roles.Count, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs index 45bd4ffc..dd0673d7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs @@ -103,7 +103,7 @@ public class CheckPathExistsQueryHandlerTests public async Task HandleAsync_WhenCalledWithNullPath_ShouldStillCallPathService() { // Arrange - CheckPathExistsQuery query = new(null!, false); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includePath: false, shouldIncludeHiddenElements: false); _mockPathService.Exists(Arg.Any(), Arg.Any()).Returns(false); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs index 08138c98..c5f7a6fb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs @@ -73,7 +73,7 @@ public class ValidatePathQueryHandlerTests public async Task HandleAsync_WhenCalledWithNullPath_ShouldReturnFalseResponse() { // Arrange - ValidatePathQuery query = new(null!); + ValidatePathQuery query = _validatePathQueryFixture.Create(includePath: false); _mockPathService.IsValidPath(Arg.Any()).Returns(false); // Act @@ -89,7 +89,7 @@ public class ValidatePathQueryHandlerTests public async Task HandleAsync_WhenCalledWithEmptyPath_ShouldReturnFalseResponse() { // Arrange - ValidatePathQuery query = new(string.Empty); + ValidatePathQuery query = _validatePathQueryFixture.Create(string.Empty); _mockPathService.IsValidPath(Arg.Any()).Returns(false); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs index 1f15f1df..880376f2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -16,12 +17,13 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Quer public class GetThumbnailQueryValidatorTests { private readonly GetThumbnailQueryValidator _validator = new(); + private readonly GetThumbnailQueryFixture _getThumbnailQueryFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - GetThumbnailQuery query = new(null!, 1); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create(includePath: false, quality: 1); // Act List result = _validator.TestValidate(query); @@ -34,7 +36,7 @@ public class GetThumbnailQueryValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - GetThumbnailQuery query = new(string.Empty, 1); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create(string.Empty, 1); // Act List result = _validator.TestValidate(query); @@ -47,7 +49,7 @@ public class GetThumbnailQueryValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - GetThumbnailQuery query = new("test", 1); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create("test", 1); // Act List result = _validator.TestValidate(query); @@ -60,7 +62,7 @@ public class GetThumbnailQueryValidatorTests public void Validate_WhenQualityIsNegative_ShouldHaveValidationError() { // Arrange - GetThumbnailQuery query = new("test", -1); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create("test", -1); // Act List result = _validator.TestValidate(query); @@ -73,7 +75,7 @@ public class GetThumbnailQueryValidatorTests public void Validate_WhenQualityIsOver100_ShouldHaveValidationError() { // Arrange - GetThumbnailQuery query = new("test", 101); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create("test", 101); // Act List result = _validator.TestValidate(query); @@ -86,7 +88,7 @@ public class GetThumbnailQueryValidatorTests public void Validate_WhenQualityIsValid_ShouldNotHaveValidationError() { // Arrange - GetThumbnailQuery query = new("test", 1); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create("test", 1); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index 7e22e841..3115e4f9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -16,6 +16,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; @@ -51,6 +52,8 @@ public class SetupApplicationCommandHandlerTests private readonly UserEntityFixture _userEntityFixture = new(); private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixtureScheduledJob = new(); /// /// Initializes a new instance of the class. @@ -78,7 +81,7 @@ public class SetupApplicationCommandHandlerTests _mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixtureScheduledJob.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _sut = new SetupApplicationCommandHandler( _mockUnitOfWork, @@ -100,7 +103,7 @@ public class SetupApplicationCommandHandlerTests string hashedPassword = Uri.EscapeDataString("hashedPassword"); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) @@ -139,7 +142,7 @@ public class SetupApplicationCommandHandlerTests string encryptedSecret = "encryptedSecret"; _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockTotpTokenGenerator.GenerateSecret() @@ -181,7 +184,7 @@ public class SetupApplicationCommandHandlerTests UserEntity existingUser = _userEntityFixture.Create(); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [existingUser], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [existingUser], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -225,7 +228,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to insert user"); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(error); @@ -249,7 +252,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to set default permissions"); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -274,7 +277,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to set default roles"); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -302,7 +305,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to set admin role permissions"); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -333,7 +336,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to set admin role to administrator account"); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -367,7 +370,7 @@ public class SetupApplicationCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to seed default scheduled jobs"); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -399,7 +402,7 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -436,7 +439,7 @@ public class SetupApplicationCommandHandlerTests ScheduledJobEntity addedScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -448,14 +451,7 @@ public class SetupApplicationCommandHandlerTests _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto - { - Data = [activeScheduledJob1, activeScheduledJob2, addedScheduledJob], - CurrentPage = 1, - PerPage = 3, - Count = 3, - NumberOfPages = 1 - })); + .Returns(Result.From(_paginatedResultDtoFixtureScheduledJob.Create(data: [activeScheduledJob1, activeScheduledJob2, addedScheduledJob], currentPage: 1, perPage: 3, count: 3, numberOfPages: 1))); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -491,7 +487,7 @@ public class SetupApplicationCommandHandlerTests // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockHashService.HashString(command.Password!) .Returns("hashedPassword"); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs index 81ef3d81..c9ec1dd1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs @@ -17,13 +17,13 @@ namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Command public class SetupApplicationCommandValidatorTests { private readonly SetupApplicationCommandValidator _validator = new(); - private readonly SetupApplicationCommandFixture _commandFixture = new(); + private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new(); [Fact] public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Username = null }; // Act @@ -37,7 +37,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Username = string.Empty }; // Act @@ -51,7 +51,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Username = " " }; // Act @@ -65,7 +65,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Password = null! }; // Act @@ -79,7 +79,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Password = string.Empty }; // Act @@ -93,7 +93,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Password = " " }; // Act @@ -107,7 +107,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { PasswordConfirm = null! }; // Act @@ -121,7 +121,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { PasswordConfirm = string.Empty }; // Act @@ -135,7 +135,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { PasswordConfirm = " " }; // Act @@ -149,7 +149,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { PasswordConfirm = "$321Bcda" }; // Act @@ -169,7 +169,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -187,7 +187,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -201,7 +201,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.Create(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs index c53ae29f..1b312140 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Contracts.Responses.UsersManagement; using Lumina.Domain.Common.Primitives; @@ -29,6 +30,7 @@ public class CheckInitializationQueryHandlerTests private readonly CheckInitializationQueryHandler _sut; private readonly CheckInitializationQueryFixture _checkInitializationQueryFixture = new(); private readonly UserEntityFixture _userEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -50,7 +52,7 @@ public class CheckInitializationQueryHandlerTests // Arrange List users = _userEntityFixture.CreateMany(); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = users, CurrentPage = 1, PerPage = users.Count, Count = users.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: users, currentPage: 1, perPage: users.Count, count: users.Count, numberOfPages: 1))); // Act InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); @@ -65,7 +67,7 @@ public class CheckInitializationQueryHandlerTests { // Arrange _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); // Act InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandlerTests.cs index 75b29816..b50265ee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandlerTests.cs @@ -59,7 +59,7 @@ public class AddAlbumCommandHandlerTests private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -362,7 +362,7 @@ public class AddAlbumCommandHandlerTests public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); Guid libraryId = Guid.Parse(command.LibraryId!); Guid artistId = Guid.Parse(command.ArtistId!); StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidatorTests.cs index e95bc068..89f88b2b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidatorTests.cs @@ -30,8 +30,9 @@ public class AddAlbumCommandValidatorTests { private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); private readonly AddAlbumCommandValidator _validator = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly TagDtoFixture _tagDtoFixture = new(); @@ -95,7 +96,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTitle: false)); // Act List result = _validator.TestValidate(command); @@ -110,7 +111,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTitleIsEmpty_ShouldHaveValidationError(string title) { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: title)); // Act List result = _validator.TestValidate(command); @@ -123,7 +124,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(command); @@ -136,7 +137,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(command); @@ -150,7 +151,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(command); @@ -163,7 +164,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act List result = _validator.TestValidate(command); @@ -176,7 +177,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(command); @@ -189,7 +190,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act List result = _validator.TestValidate(command); @@ -202,7 +203,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeDescription: false)); // Act List result = _validator.TestValidate(command); @@ -215,7 +216,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); // Act List result = _validator.TestValidate(command); @@ -228,7 +229,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseTypeIsNotDefined_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseTypes: [(MusicReleaseType)999])); // Act List result = _validator.TestValidate(command); @@ -241,7 +242,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseTypeIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseTypes: false)); // Act List result = _validator.TestValidate(command); @@ -254,7 +255,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseTypeIsDefined_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseTypes: [MusicReleaseType.Album])); // Act List result = _validator.TestValidate(command); @@ -267,7 +268,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseStatusIsNotDefined_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999)); // Act List result = _validator.TestValidate(command); @@ -280,7 +281,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseStatusIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseStatus: false)); // Act List result = _validator.TestValidate(command); @@ -293,7 +294,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseStatusIsDefined_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official)); // Act List result = _validator.TestValidate(command); @@ -308,7 +309,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalDiscs: totalDiscs)); // Act List result = _validator.TestValidate(command); @@ -321,7 +322,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTotalDiscsIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTotalDiscs: false)); // Act List result = _validator.TestValidate(command); @@ -334,7 +335,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTotalDiscsIsPositive_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: 2)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalDiscs: 2)); // Act List result = _validator.TestValidate(command); @@ -349,7 +350,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalTracks: totalTracks)); // Act List result = _validator.TestValidate(command); @@ -362,7 +363,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTotalTracksIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTotalTracks: false)); // Act List result = _validator.TestValidate(command); @@ -375,7 +376,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTotalTracksIsPositive_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: 10)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalTracks: 10)); // Act List result = _validator.TestValidate(command); @@ -388,7 +389,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act List result = _validator.TestValidate(command); @@ -401,7 +402,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); // Act List result = _validator.TestValidate(command); @@ -414,7 +415,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); // Act List result = _validator.TestValidate(command); @@ -427,7 +428,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -440,7 +441,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); // Act List result = _validator.TestValidate(command); @@ -453,7 +454,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); // Act List result = _validator.TestValidate(command); @@ -466,7 +467,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -479,7 +480,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -492,7 +493,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); // Act List result = _validator.TestValidate(command); @@ -505,7 +506,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -518,7 +519,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -531,7 +532,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); // Act List result = _validator.TestValidate(command); @@ -544,7 +545,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); // Act List result = _validator.TestValidate(command); @@ -557,7 +558,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -570,7 +571,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -583,7 +584,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); // Act List result = _validator.TestValidate(command); @@ -596,7 +597,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); // Act List result = _validator.TestValidate(command); @@ -609,7 +610,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeGenres: false)); // Act List result = _validator.TestValidate(command); @@ -622,7 +623,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(command); @@ -635,7 +636,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(command); @@ -648,7 +649,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(command); @@ -663,7 +664,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTags: false)); // Act List result = _validator.TestValidate(command); @@ -676,7 +677,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(command); @@ -689,7 +690,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(command); @@ -702,7 +703,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(command); @@ -717,7 +718,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeLanguage: false)); // Act List result = _validator.TestValidate(command); @@ -730,7 +731,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -743,7 +744,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(command); @@ -756,7 +757,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); // Act List result = _validator.TestValidate(command); @@ -769,7 +770,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -782,7 +783,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -795,7 +796,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(command); @@ -808,7 +809,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -821,7 +822,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act List result = _validator.TestValidate(command); @@ -834,7 +835,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -847,7 +848,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(command); @@ -860,7 +861,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -873,7 +874,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -886,7 +887,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(command); @@ -899,7 +900,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -925,7 +926,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenMediaFormatIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); // Act List result = _validator.TestValidate(command); @@ -951,7 +952,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenCatalogNumberExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(catalogNumbers: [new Faker().Random.String2(51)]); // Act List result = _validator.TestValidate(command); @@ -964,7 +965,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenCatalogNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); // Act List result = _validator.TestValidate(command); @@ -977,7 +978,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenCatalogNumberIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50)); + AddAlbumCommand command = _addAlbumCommandFixture.Create(catalogNumbers: [new Faker().Random.String2(50)]); // Act List result = _validator.TestValidate(command); @@ -1035,7 +1036,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenBarcodeIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); // Act List result = _validator.TestValidate(command); @@ -1087,7 +1088,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenMusicBrainzIdsAreNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); // Act List result = _validator.TestValidate(command); @@ -1376,7 +1377,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackTitleIsNull_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTitle: false))]); // Act List result = _validator.TestValidate(command); @@ -1389,7 +1390,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); // Act List result = _validator.TestValidate(command); @@ -1402,7 +1403,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); // Act List result = _validator.TestValidate(command); @@ -1416,7 +1417,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); // Act List result = _validator.TestValidate(command); @@ -1429,7 +1430,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); // Act List result = _validator.TestValidate(command); @@ -1442,7 +1443,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeReleaseInfo: false))]); // Act List result = _validator.TestValidate(command); @@ -1455,7 +1456,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); // Act List result = _validator.TestValidate(command); @@ -1468,7 +1469,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); // Act List result = _validator.TestValidate(command); @@ -1481,7 +1482,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); // Act List result = _validator.TestValidate(command); @@ -1494,7 +1495,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); // Act List result = _validator.TestValidate(command); @@ -1507,7 +1508,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -1520,7 +1521,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -1533,7 +1534,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))]); // Act List result = _validator.TestValidate(command); @@ -1546,7 +1547,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -1559,7 +1560,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))]); // Act List result = _validator.TestValidate(command); @@ -1572,7 +1573,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackGenresIsNull_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeGenres: false))]); // Act List result = _validator.TestValidate(command); @@ -1585,7 +1586,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); // Act List result = _validator.TestValidate(command); @@ -1598,7 +1599,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))]); // Act List result = _validator.TestValidate(command); @@ -1611,7 +1612,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackTagsIsNull_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTags: false))]); // Act List result = _validator.TestValidate(command); @@ -1624,7 +1625,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); // Act List result = _validator.TestValidate(command); @@ -1637,7 +1638,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))]); // Act List result = _validator.TestValidate(command); @@ -1650,7 +1651,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -1663,7 +1664,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); // Act List result = _validator.TestValidate(command); @@ -1676,7 +1677,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -1689,7 +1690,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -1702,7 +1703,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -1715,7 +1716,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -1728,7 +1729,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -1741,7 +1742,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -1780,7 +1781,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.Empty))]); // Act List result = _validator.TestValidate(command); @@ -1793,7 +1794,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackMusicBrainzIdsAreNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)]); // Act List result = _validator.TestValidate(command); @@ -1862,7 +1863,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenDiscNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)]); // Act List result = _validator.TestValidate(command); @@ -1901,7 +1902,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenScriptIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)]); // Act List result = _validator.TestValidate(command); @@ -1940,7 +1941,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenKeyIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)]); // Act List result = _validator.TestValidate(command); @@ -1981,7 +1982,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenBpmIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)]); // Act List result = _validator.TestValidate(command); @@ -2007,7 +2008,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenWorkExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(256))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(256)))]); // Act List result = _validator.TestValidate(command); @@ -2020,7 +2021,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenWorkIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)]); // Act List result = _validator.TestValidate(command); @@ -2033,7 +2034,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenWorkIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(255))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(255)))]); // Act List result = _validator.TestValidate(command); @@ -2251,7 +2252,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalTitle: false))]); // Act List result = _validator.TestValidate(command); @@ -2264,7 +2265,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeDescription: false))]); // Act List result = _validator.TestValidate(command); @@ -2277,7 +2278,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReleaseInfoIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -2292,7 +2293,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackGenresAreValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))]); // Act List result = _validator.TestValidate(command); @@ -2307,7 +2308,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackTagsAreValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))]); // Act List result = _validator.TestValidate(command); @@ -2322,7 +2323,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeLanguage: false))]); // Act List result = _validator.TestValidate(command); @@ -2335,7 +2336,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); // Act List result = _validator.TestValidate(command); @@ -2348,7 +2349,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); // Act List result = _validator.TestValidate(command); @@ -2361,7 +2362,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalLanguage: false))]); // Act List result = _validator.TestValidate(command); @@ -2374,7 +2375,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); // Act List result = _validator.TestValidate(command); @@ -2387,7 +2388,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -2400,7 +2401,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); // Act List result = _validator.TestValidate(command); @@ -2413,7 +2414,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackMusicBrainzIdsAreValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), musicBrainzWorkId: Guid.NewGuid())]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.NewGuid()))]); // Act List result = _validator.TestValidate(command); @@ -2426,7 +2427,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); // Act List result = _validator.TestValidate(command); @@ -2440,7 +2441,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); // Act List result = _validator.TestValidate(command); @@ -2453,7 +2454,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); // Act List result = _validator.TestValidate(command); @@ -2466,7 +2467,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); // Act List result = _validator.TestValidate(command); @@ -2480,7 +2481,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); // Act List result = _validator.TestValidate(command); @@ -2493,7 +2494,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenReleaseVersionIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); // Act List result = _validator.TestValidate(command); @@ -2506,7 +2507,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); // Act List result = _validator.TestValidate(command); @@ -2519,7 +2520,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); // Act List result = _validator.TestValidate(command); @@ -2532,7 +2533,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -2545,7 +2546,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -2558,7 +2559,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))]); // Act List result = _validator.TestValidate(command); @@ -2571,7 +2572,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -2584,7 +2585,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))]); // Act List result = _validator.TestValidate(command); @@ -2597,7 +2598,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -2610,7 +2611,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))]); // Act List result = _validator.TestValidate(command); @@ -2623,7 +2624,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2637,7 +2638,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2650,7 +2651,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); // Act List result = _validator.TestValidate(command); @@ -2663,7 +2664,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2677,7 +2678,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2690,7 +2691,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenMoodsIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)]); // Act List result = _validator.TestValidate(command); @@ -2703,7 +2704,7 @@ public class AddAlbumCommandValidatorTests public void Validate_WhenIsrcsIsNull_ShouldNotHaveValidationError() { // Arrange - AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)]); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandlerTests.cs index 8b335b56..b091d53b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandlerTests.cs @@ -54,7 +54,7 @@ public class UpdateAlbumCommandHandlerTests private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); /// @@ -369,7 +369,7 @@ public class UpdateAlbumCommandHandlerTests libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString(), - metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidatorTests.cs index 490c05bc..057357a2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidatorTests.cs @@ -28,7 +28,7 @@ public class UpdateAlbumCommandValidatorTests { private readonly UpdateAlbumCommandFixture _updateAlbumCommandFixture = new(); private readonly UpdateAlbumCommandValidator _validator = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly TagDtoFixture _tagDtoFixture = new(); @@ -107,7 +107,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTitle: false)); // Act List result = _validator.TestValidate(command); @@ -122,7 +122,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTitleIsEmpty_ShouldHaveValidationError(string title) { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: title)); // Act List result = _validator.TestValidate(command); @@ -135,7 +135,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(command); @@ -148,7 +148,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(command); @@ -162,7 +162,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(command); @@ -175,7 +175,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act List result = _validator.TestValidate(command); @@ -188,7 +188,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(command); @@ -201,7 +201,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act List result = _validator.TestValidate(command); @@ -214,7 +214,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeDescription: false)); // Act List result = _validator.TestValidate(command); @@ -227,7 +227,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); // Act List result = _validator.TestValidate(command); @@ -240,7 +240,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseTypeIsNotDefined_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseTypes: [(MusicReleaseType)999])); // Act List result = _validator.TestValidate(command); @@ -253,7 +253,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseTypeIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseTypes: false)); // Act List result = _validator.TestValidate(command); @@ -266,7 +266,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseTypeIsDefined_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseTypes: [MusicReleaseType.Album])); // Act List result = _validator.TestValidate(command); @@ -279,7 +279,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseStatusIsNotDefined_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999)); // Act List result = _validator.TestValidate(command); @@ -292,7 +292,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseStatusIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseStatus: false)); // Act List result = _validator.TestValidate(command); @@ -305,7 +305,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseStatusIsDefined_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official)); // Act List result = _validator.TestValidate(command); @@ -320,7 +320,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalDiscs: totalDiscs)); // Act List result = _validator.TestValidate(command); @@ -333,7 +333,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTotalDiscsIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTotalDiscs: false)); // Act List result = _validator.TestValidate(command); @@ -346,7 +346,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTotalDiscsIsPositive_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: 2)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalDiscs: 2)); // Act List result = _validator.TestValidate(command); @@ -361,7 +361,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalTracks: totalTracks)); // Act List result = _validator.TestValidate(command); @@ -374,7 +374,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTotalTracksIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTotalTracks: false)); // Act List result = _validator.TestValidate(command); @@ -387,7 +387,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTotalTracksIsPositive_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: 10)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalTracks: 10)); // Act List result = _validator.TestValidate(command); @@ -400,7 +400,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act List result = _validator.TestValidate(command); @@ -413,7 +413,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); // Act List result = _validator.TestValidate(command); @@ -426,7 +426,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); // Act List result = _validator.TestValidate(command); @@ -439,7 +439,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -452,7 +452,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); // Act List result = _validator.TestValidate(command); @@ -465,7 +465,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); // Act List result = _validator.TestValidate(command); @@ -478,7 +478,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -491,7 +491,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -504,7 +504,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); // Act List result = _validator.TestValidate(command); @@ -517,7 +517,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -530,7 +530,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -543,7 +543,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); // Act List result = _validator.TestValidate(command); @@ -556,7 +556,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); // Act List result = _validator.TestValidate(command); @@ -569,7 +569,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -582,7 +582,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -595,7 +595,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); // Act List result = _validator.TestValidate(command); @@ -608,7 +608,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); // Act List result = _validator.TestValidate(command); @@ -621,7 +621,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeGenres: false)); // Act List result = _validator.TestValidate(command); @@ -634,7 +634,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(command); @@ -647,7 +647,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(command); @@ -660,7 +660,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(command); @@ -675,7 +675,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTags: false)); // Act List result = _validator.TestValidate(command); @@ -688,7 +688,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(command); @@ -701,7 +701,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(command); @@ -714,7 +714,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(command); @@ -729,7 +729,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeLanguage: false)); // Act List result = _validator.TestValidate(command); @@ -742,7 +742,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -755,7 +755,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(command); @@ -768,7 +768,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); // Act List result = _validator.TestValidate(command); @@ -781,7 +781,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -794,7 +794,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -807,7 +807,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(command); @@ -820,7 +820,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -833,7 +833,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act List result = _validator.TestValidate(command); @@ -846,7 +846,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -859,7 +859,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(command); @@ -872,7 +872,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -885,7 +885,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -898,7 +898,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(command); @@ -911,7 +911,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -937,7 +937,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenMediaFormatIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); // Act List result = _validator.TestValidate(command); @@ -963,7 +963,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenCatalogNumberExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(catalogNumbers: [new Faker().Random.String2(51)]); // Act List result = _validator.TestValidate(command); @@ -976,7 +976,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenCatalogNumberIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); // Act List result = _validator.TestValidate(command); @@ -989,7 +989,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenCatalogNumberIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(catalogNumbers: [new Faker().Random.String2(50)]); // Act List result = _validator.TestValidate(command); @@ -1047,7 +1047,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenBarcodeIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); // Act List result = _validator.TestValidate(command); @@ -1099,7 +1099,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenMusicBrainzIdsAreNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); // Act List result = _validator.TestValidate(command); @@ -1307,7 +1307,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); // Act List result = _validator.TestValidate(command); @@ -1321,7 +1321,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); // Act List result = _validator.TestValidate(command); @@ -1334,7 +1334,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); // Act List result = _validator.TestValidate(command); @@ -1347,7 +1347,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); // Act List result = _validator.TestValidate(command); @@ -1361,7 +1361,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); // Act List result = _validator.TestValidate(command); @@ -1374,7 +1374,7 @@ public class UpdateAlbumCommandValidatorTests public void Validate_WhenReleaseVersionIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandlerTests.cs index 3d13c57e..7ee1169b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandlerTests.cs @@ -20,6 +20,7 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Al using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -53,6 +54,7 @@ public class AddArtistCommandHandlerTests private readonly AddArtistCommandHandler _sut; private readonly Guid _userId; private readonly AddArtistCommandFixture _addArtistCommandFixture = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); private readonly ArtistEntityFixture _artistEntityFixture = new(); @@ -275,7 +277,7 @@ public class AddArtistCommandHandlerTests public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(name: string.Empty); + AddArtistCommand command = _addArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: string.Empty)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -384,7 +386,7 @@ public class AddArtistCommandHandlerTests Assert.NotNull(persistedArtist); Assert.Equal(insertedArtist!.Id, persistedArtist!.Id); Assert.Equal(persistedArtist.Id, result.Value.Id); - Assert.Equal(persistedArtist.Name, result.Value.Name); + Assert.Equal(persistedArtist.Name, result.Value.Metadata.Name); await _mockArtistRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidatorTests.cs index b81d44b5..c642bbba 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidatorTests.cs @@ -31,8 +31,10 @@ public class AddArtistCommandValidatorTests private readonly AddArtistCommandFixture _addArtistCommandFixture = new(); private readonly AddArtistCommandValidator _validator = new(); private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly TagDtoFixture _tagDtoFixture = new(); @@ -65,7 +67,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenNameIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(includeName: false); + AddArtistCommand command = _addArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(includeName: false)); // Act List result = _validator.TestValidate(command); @@ -80,7 +82,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenNameIsEmpty_ShouldHaveValidationError(string name) { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(name: name); + AddArtistCommand command = _addArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: name)); // Act List result = _validator.TestValidate(command); @@ -93,7 +95,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenNameExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(name: new Faker().Random.String2(256)); + AddArtistCommand command = _addArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: new Faker().Random.String2(256))); // Act List result = _validator.TestValidate(command); @@ -106,7 +108,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(name: new Faker().Random.String2(255)); + AddArtistCommand command = _addArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: new Faker().Random.String2(255))); // Act List result = _validator.TestValidate(command); @@ -278,7 +280,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTitleIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTitle: false))]); // Act List result = _validator.TestValidate(command); @@ -293,7 +295,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTitleIsEmpty_ShouldHaveValidationError(string title) { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: title))]); // Act List result = _validator.TestValidate(command); @@ -306,7 +308,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); // Act List result = _validator.TestValidate(command); @@ -319,7 +321,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); // Act List result = _validator.TestValidate(command); @@ -333,7 +335,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); // Act List result = _validator.TestValidate(command); @@ -346,7 +348,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); // Act List result = _validator.TestValidate(command); @@ -359,7 +361,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseTypeIsNotDefined_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseTypes: [(MusicReleaseType)999]))]); // Act List result = _validator.TestValidate(command); @@ -372,7 +374,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseTypeIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseTypes: false))]); // Act List result = _validator.TestValidate(command); @@ -385,7 +387,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseTypeIsDefined_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseTypes: [MusicReleaseType.Album]))]); // Act List result = _validator.TestValidate(command); @@ -398,7 +400,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseStatusIsNotDefined_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999))]); // Act List result = _validator.TestValidate(command); @@ -411,7 +413,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseStatusIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseStatus: false))]); // Act List result = _validator.TestValidate(command); @@ -424,7 +426,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseStatusIsDefined_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official))]); // Act List result = _validator.TestValidate(command); @@ -439,7 +441,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalDiscs: totalDiscs))]); // Act List result = _validator.TestValidate(command); @@ -452,7 +454,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTotalDiscsIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTotalDiscs: false))]); // Act List result = _validator.TestValidate(command); @@ -465,7 +467,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTotalDiscsIsPositive_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: 2))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalDiscs: 2))]); // Act List result = _validator.TestValidate(command); @@ -480,7 +482,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalTracks: totalTracks))]); // Act List result = _validator.TestValidate(command); @@ -493,7 +495,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTotalTracksIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTotalTracks: false))]); // Act List result = _validator.TestValidate(command); @@ -506,7 +508,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTotalTracksIsPositive_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: 10))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalTracks: 10))]); // Act List result = _validator.TestValidate(command); @@ -519,7 +521,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseInfo: false))]); // Act List result = _validator.TestValidate(command); @@ -532,7 +534,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); // Act List result = _validator.TestValidate(command); @@ -545,7 +547,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); // Act List result = _validator.TestValidate(command); @@ -558,7 +560,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); // Act List result = _validator.TestValidate(command); @@ -571,7 +573,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); // Act List result = _validator.TestValidate(command); @@ -584,7 +586,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -597,7 +599,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -610,7 +612,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))]); // Act List result = _validator.TestValidate(command); @@ -623,7 +625,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -636,7 +638,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))]); // Act List result = _validator.TestValidate(command); @@ -649,7 +651,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumGenresIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeGenres: false))]); // Act List result = _validator.TestValidate(command); @@ -662,7 +664,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); // Act List result = _validator.TestValidate(command); @@ -675,7 +677,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))]); // Act List result = _validator.TestValidate(command); @@ -688,7 +690,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTagsIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTags: false))]); // Act List result = _validator.TestValidate(command); @@ -701,7 +703,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); // Act List result = _validator.TestValidate(command); @@ -714,7 +716,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))]); // Act List result = _validator.TestValidate(command); @@ -727,7 +729,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -740,7 +742,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); // Act List result = _validator.TestValidate(command); @@ -753,7 +755,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -766,7 +768,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -779,7 +781,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -792,7 +794,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeLanguage: false))]); // Act List result = _validator.TestValidate(command); @@ -805,7 +807,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -818,7 +820,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -831,7 +833,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -857,7 +859,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumMediaFormatIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); // Act List result = _validator.TestValidate(command); @@ -883,7 +885,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumCatalogNumberExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumbers: [new Faker().Random.String2(51)])]); // Act List result = _validator.TestValidate(command); @@ -896,7 +898,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumCatalogNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); // Act List result = _validator.TestValidate(command); @@ -954,7 +956,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumBarcodeIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); // Act List result = _validator.TestValidate(command); @@ -1006,7 +1008,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumMusicBrainzIdsAreNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); // Act List result = _validator.TestValidate(command); @@ -1247,7 +1249,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackTitleIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTitle: false))])]); // Act List result = _validator.TestValidate(command); @@ -1260,7 +1262,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))])]); // Act List result = _validator.TestValidate(command); @@ -1273,7 +1275,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))])]); // Act List result = _validator.TestValidate(command); @@ -1287,7 +1289,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))])]); // Act List result = _validator.TestValidate(command); @@ -1300,7 +1302,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))])]); // Act List result = _validator.TestValidate(command); @@ -1313,7 +1315,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeReleaseInfo: false))])]); // Act List result = _validator.TestValidate(command); @@ -1326,7 +1328,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))])]); // Act List result = _validator.TestValidate(command); @@ -1339,7 +1341,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))])]); // Act List result = _validator.TestValidate(command); @@ -1352,7 +1354,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))])]); // Act List result = _validator.TestValidate(command); @@ -1365,7 +1367,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))])]); // Act List result = _validator.TestValidate(command); @@ -1378,7 +1380,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))])]); // Act List result = _validator.TestValidate(command); @@ -1391,7 +1393,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -1404,7 +1406,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))])]); // Act List result = _validator.TestValidate(command); @@ -1417,7 +1419,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -1430,7 +1432,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))])]); // Act List result = _validator.TestValidate(command); @@ -1443,7 +1445,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackGenresIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeGenres: false))])]); // Act List result = _validator.TestValidate(command); @@ -1456,7 +1458,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))])]); // Act List result = _validator.TestValidate(command); @@ -1469,7 +1471,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); // Act List result = _validator.TestValidate(command); @@ -1482,7 +1484,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackTagsIsNull_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTags: false))])]); // Act List result = _validator.TestValidate(command); @@ -1495,7 +1497,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))])]); // Act List result = _validator.TestValidate(command); @@ -1508,7 +1510,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); // Act List result = _validator.TestValidate(command); @@ -1521,7 +1523,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); // Act List result = _validator.TestValidate(command); @@ -1534,7 +1536,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))])]); // Act List result = _validator.TestValidate(command); @@ -1547,7 +1549,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); // Act List result = _validator.TestValidate(command); @@ -1560,7 +1562,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))])]); // Act List result = _validator.TestValidate(command); @@ -1573,7 +1575,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); // Act List result = _validator.TestValidate(command); @@ -1586,7 +1588,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); // Act List result = _validator.TestValidate(command); @@ -1599,7 +1601,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); // Act List result = _validator.TestValidate(command); @@ -1612,7 +1614,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); // Act List result = _validator.TestValidate(command); @@ -1651,7 +1653,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty)])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.Empty))])]); // Act List result = _validator.TestValidate(command); @@ -1748,7 +1750,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackWorkExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(256))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(256)))])]); // Act List result = _validator.TestValidate(command); @@ -1895,7 +1897,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeOriginalTitle: false))]); // Act List result = _validator.TestValidate(command); @@ -1908,7 +1910,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); // Act List result = _validator.TestValidate(command); @@ -1921,7 +1923,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeDescription: false))]); // Act List result = _validator.TestValidate(command); @@ -1934,7 +1936,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); // Act List result = _validator.TestValidate(command); @@ -1947,7 +1949,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -1960,7 +1962,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -1973,7 +1975,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))]); // Act List result = _validator.TestValidate(command); @@ -1986,7 +1988,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -1999,7 +2001,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))]); // Act List result = _validator.TestValidate(command); @@ -2012,7 +2014,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -2025,7 +2027,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))]); // Act List result = _validator.TestValidate(command); @@ -2038,7 +2040,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumGenresAreValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))]); // Act List result = _validator.TestValidate(command); @@ -2053,7 +2055,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumTagsAreValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))]); // Act List result = _validator.TestValidate(command); @@ -2068,7 +2070,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); // Act List result = _validator.TestValidate(command); @@ -2081,7 +2083,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2095,7 +2097,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); // Act List result = _validator.TestValidate(command); @@ -2108,7 +2110,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2121,7 +2123,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeOriginalLanguage: false))]); // Act List result = _validator.TestValidate(command); @@ -2134,7 +2136,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); // Act List result = _validator.TestValidate(command); @@ -2147,7 +2149,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2161,7 +2163,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); // Act List result = _validator.TestValidate(command); @@ -2174,7 +2176,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2187,7 +2189,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenAlbumCatalogNumberIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50))]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumbers: [new Faker().Random.String2(50)])]); // Act List result = _validator.TestValidate(command); @@ -2245,7 +2247,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalTitle: false))])]); // Act List result = _validator.TestValidate(command); @@ -2258,7 +2260,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))])]); // Act List result = _validator.TestValidate(command); @@ -2271,7 +2273,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeDescription: false))])]); // Act List result = _validator.TestValidate(command); @@ -2284,7 +2286,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))])]); // Act List result = _validator.TestValidate(command); @@ -2297,7 +2299,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2310,7 +2312,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2323,7 +2325,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))])]); // Act List result = _validator.TestValidate(command); @@ -2336,7 +2338,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2349,7 +2351,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))])]); // Act List result = _validator.TestValidate(command); @@ -2362,7 +2364,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2375,7 +2377,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))])]); // Act List result = _validator.TestValidate(command); @@ -2388,7 +2390,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackGenresAreValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); // Act List result = _validator.TestValidate(command); @@ -2403,7 +2405,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackTagsAreValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); // Act List result = _validator.TestValidate(command); @@ -2418,7 +2420,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeLanguage: false))])]); // Act List result = _validator.TestValidate(command); @@ -2431,7 +2433,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); // Act List result = _validator.TestValidate(command); @@ -2444,7 +2446,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); // Act List result = _validator.TestValidate(command); @@ -2458,7 +2460,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2471,7 +2473,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); // Act List result = _validator.TestValidate(command); @@ -2484,7 +2486,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalLanguage: false))])]); // Act List result = _validator.TestValidate(command); @@ -2497,7 +2499,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); // Act List result = _validator.TestValidate(command); @@ -2510,7 +2512,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); // Act List result = _validator.TestValidate(command); @@ -2524,7 +2526,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2537,7 +2539,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); // Act List result = _validator.TestValidate(command); @@ -2550,7 +2552,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackMusicBrainzIdsAreValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), musicBrainzWorkId: Guid.NewGuid())])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.NewGuid()))])]); // Act List result = _validator.TestValidate(command); @@ -2576,7 +2578,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenDiscNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2602,7 +2604,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackScriptIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2628,7 +2630,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackKeyIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2654,7 +2656,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackBpmIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2680,7 +2682,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackWorkIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2693,7 +2695,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackWorkIsValid_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(255))])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(255)))])]); // Act List result = _validator.TestValidate(command); @@ -2719,7 +2721,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackMoodsIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2745,7 +2747,7 @@ public class AddArtistCommandValidatorTests public void Validate_WhenTrackIsrcsIsNull_ShouldNotHaveValidationError() { // Arrange - AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandlerTests.cs index 35ab36e6..c082ec4d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandlerTests.cs @@ -19,6 +19,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -52,6 +53,7 @@ public class UpdateArtistCommandHandlerTests private readonly UpdateArtistCommandHandler _sut; private readonly Guid _userId; private readonly UpdateArtistCommandFixture _updateArtistCommandFixture = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); private readonly ArtistEntityFixture _artistEntityFixture = new(); @@ -383,7 +385,7 @@ public class UpdateArtistCommandHandlerTests Guid artistId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); - UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), name: string.Empty); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), metadata: _musicArtistMetadataDtoFixture.Create(name: string.Empty)); StubArtistReads(existingArtist); // Act @@ -530,7 +532,7 @@ public class UpdateArtistCommandHandlerTests Assert.False(result.IsFailure); Assert.NotNull(updatedArtist); Assert.Equal(artistId, result.Value.Id); - Assert.Equal(persistedArtist.Name, result.Value.Name); + Assert.Equal(persistedArtist.Name, result.Value.Metadata.Name); await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidatorTests.cs index 6db619ee..a5cd1299 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidatorTests.cs @@ -31,8 +31,10 @@ public class UpdateArtistCommandValidatorTests private readonly UpdateArtistCommandFixture _updateArtistCommandFixture = new(); private readonly UpdateArtistCommandValidator _validator = new(); private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); - private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); + private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly TagDtoFixture _tagDtoFixture = new(); @@ -83,7 +85,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenNameIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeName: false); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(includeName: false)); // Act List result = _validator.TestValidate(command); @@ -98,7 +100,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenNameIsEmpty_ShouldHaveValidationError(string name) { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: name); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: name)); // Act List result = _validator.TestValidate(command); @@ -111,7 +113,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenNameExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: new Faker().Random.String2(256)); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: new Faker().Random.String2(256))); // Act List result = _validator.TestValidate(command); @@ -124,7 +126,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: new Faker().Random.String2(255)); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: new Faker().Random.String2(255))); // Act List result = _validator.TestValidate(command); @@ -335,7 +337,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTitleIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTitle: false))]); // Act List result = _validator.TestValidate(command); @@ -350,7 +352,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTitleIsEmpty_ShouldHaveValidationError(string title) { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: title))]); // Act List result = _validator.TestValidate(command); @@ -363,7 +365,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); // Act List result = _validator.TestValidate(command); @@ -376,7 +378,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTitleIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); // Act List result = _validator.TestValidate(command); @@ -390,7 +392,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); // Act List result = _validator.TestValidate(command); @@ -403,7 +405,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeOriginalTitle: false))]); // Act List result = _validator.TestValidate(command); @@ -416,7 +418,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); // Act List result = _validator.TestValidate(command); @@ -429,7 +431,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeDescription: false))]); // Act List result = _validator.TestValidate(command); @@ -442,7 +444,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseTypeIsNotDefined_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseTypes: [(MusicReleaseType)999]))]); // Act List result = _validator.TestValidate(command); @@ -455,7 +457,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseTypeIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseTypes: false))]); // Act List result = _validator.TestValidate(command); @@ -468,7 +470,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseTypeIsDefined_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseTypes: [MusicReleaseType.Album]))]); // Act List result = _validator.TestValidate(command); @@ -481,7 +483,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseStatusIsNotDefined_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999))]); // Act List result = _validator.TestValidate(command); @@ -494,7 +496,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseStatusIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseStatus: false))]); // Act List result = _validator.TestValidate(command); @@ -507,7 +509,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseStatusIsDefined_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official))]); // Act List result = _validator.TestValidate(command); @@ -522,7 +524,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalDiscs: totalDiscs))]); // Act List result = _validator.TestValidate(command); @@ -535,7 +537,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTotalDiscsIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTotalDiscs: false))]); // Act List result = _validator.TestValidate(command); @@ -550,7 +552,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(totalTracks: totalTracks))]); // Act List result = _validator.TestValidate(command); @@ -563,7 +565,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTotalTracksIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTotalTracks: false))]); // Act List result = _validator.TestValidate(command); @@ -576,7 +578,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeReleaseInfo: false))]); // Act List result = _validator.TestValidate(command); @@ -589,7 +591,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); // Act List result = _validator.TestValidate(command); @@ -602,7 +604,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); // Act List result = _validator.TestValidate(command); @@ -615,7 +617,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); // Act List result = _validator.TestValidate(command); @@ -628,7 +630,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); // Act List result = _validator.TestValidate(command); @@ -641,7 +643,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -654,7 +656,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -667,7 +669,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -680,7 +682,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))]); // Act List result = _validator.TestValidate(command); @@ -693,7 +695,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))]); // Act List result = _validator.TestValidate(command); @@ -706,7 +708,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -719,7 +721,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -732,7 +734,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))]); // Act List result = _validator.TestValidate(command); @@ -745,7 +747,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))]); // Act List result = _validator.TestValidate(command); @@ -758,7 +760,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumGenresIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeGenres: false))]); // Act List result = _validator.TestValidate(command); @@ -771,7 +773,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); // Act List result = _validator.TestValidate(command); @@ -784,7 +786,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))]); // Act List result = _validator.TestValidate(command); @@ -797,7 +799,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumGenresAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))]); // Act List result = _validator.TestValidate(command); @@ -812,7 +814,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTagsIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeTags: false))]); // Act List result = _validator.TestValidate(command); @@ -825,7 +827,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); // Act List result = _validator.TestValidate(command); @@ -838,7 +840,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))]); // Act List result = _validator.TestValidate(command); @@ -851,7 +853,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumTagsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))]); // Act List result = _validator.TestValidate(command); @@ -866,7 +868,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeLanguage: false))]); // Act List result = _validator.TestValidate(command); @@ -879,7 +881,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -892,7 +894,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); // Act List result = _validator.TestValidate(command); @@ -905,7 +907,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); // Act List result = _validator.TestValidate(command); @@ -918,7 +920,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -931,7 +933,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -944,7 +946,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); // Act List result = _validator.TestValidate(command); @@ -957,7 +959,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -970,7 +972,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(includeOriginalLanguage: false))]); // Act List result = _validator.TestValidate(command); @@ -983,7 +985,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -996,7 +998,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); // Act List result = _validator.TestValidate(command); @@ -1009,7 +1011,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); // Act List result = _validator.TestValidate(command); @@ -1022,7 +1024,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -1035,7 +1037,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); // Act List result = _validator.TestValidate(command); @@ -1048,7 +1050,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); // Act List result = _validator.TestValidate(command); @@ -1074,7 +1076,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumMediaFormatIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); // Act List result = _validator.TestValidate(command); @@ -1100,7 +1102,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumCatalogNumberExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumbers: [new Faker().Random.String2(51)])]); // Act List result = _validator.TestValidate(command); @@ -1113,7 +1115,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumCatalogNumberIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); // Act List result = _validator.TestValidate(command); @@ -1171,7 +1173,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumBarcodeIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); // Act List result = _validator.TestValidate(command); @@ -1223,7 +1225,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumMusicBrainzIdsAreNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumbers: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); // Act List result = _validator.TestValidate(command); @@ -1548,7 +1550,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackTitleIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTitle: false))])]); // Act List result = _validator.TestValidate(command); @@ -1561,7 +1563,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))])]); // Act List result = _validator.TestValidate(command); @@ -1574,7 +1576,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))])]); // Act List result = _validator.TestValidate(command); @@ -1587,7 +1589,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))])]); // Act List result = _validator.TestValidate(command); @@ -1600,7 +1602,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeReleaseInfo: false))])]); // Act List result = _validator.TestValidate(command); @@ -1613,7 +1615,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))])]); // Act List result = _validator.TestValidate(command); @@ -1626,7 +1628,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))])]); // Act List result = _validator.TestValidate(command); @@ -1639,7 +1641,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))])]); // Act List result = _validator.TestValidate(command); @@ -1652,7 +1654,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))])]); // Act List result = _validator.TestValidate(command); @@ -1665,7 +1667,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))])]); // Act List result = _validator.TestValidate(command); @@ -1678,7 +1680,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -1691,7 +1693,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))])]); // Act List result = _validator.TestValidate(command); @@ -1704,7 +1706,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -1717,7 +1719,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))])]); // Act List result = _validator.TestValidate(command); @@ -1730,7 +1732,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackGenresIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeGenres: false))])]); // Act List result = _validator.TestValidate(command); @@ -1743,7 +1745,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))])]); // Act List result = _validator.TestValidate(command); @@ -1756,7 +1758,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); // Act List result = _validator.TestValidate(command); @@ -1769,7 +1771,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackTagsIsNull_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTags: false))])]); // Act List result = _validator.TestValidate(command); @@ -1782,7 +1784,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))])]); // Act List result = _validator.TestValidate(command); @@ -1795,7 +1797,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); // Act List result = _validator.TestValidate(command); @@ -1808,7 +1810,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); // Act List result = _validator.TestValidate(command); @@ -1821,7 +1823,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))])]); // Act List result = _validator.TestValidate(command); @@ -1834,7 +1836,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); // Act List result = _validator.TestValidate(command); @@ -1847,7 +1849,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))])]); // Act List result = _validator.TestValidate(command); @@ -1860,7 +1862,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); // Act List result = _validator.TestValidate(command); @@ -1873,7 +1875,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); // Act List result = _validator.TestValidate(command); @@ -1886,7 +1888,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); // Act List result = _validator.TestValidate(command); @@ -1899,7 +1901,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); // Act List result = _validator.TestValidate(command); @@ -1938,7 +1940,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty)])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.Empty))])]); // Act List result = _validator.TestValidate(command); @@ -2035,7 +2037,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackWorkExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(256))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(256)))])]); // Act List result = _validator.TestValidate(command); @@ -2182,7 +2184,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); // Act List result = _validator.TestValidate(command); @@ -2195,7 +2197,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); // Act List result = _validator.TestValidate(command); @@ -2208,7 +2210,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -2221,7 +2223,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); // Act List result = _validator.TestValidate(command); @@ -2234,7 +2236,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))]); // Act List result = _validator.TestValidate(command); @@ -2247,7 +2249,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2261,7 +2263,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2274,7 +2276,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); // Act List result = _validator.TestValidate(command); @@ -2287,7 +2289,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2301,7 +2303,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); // Act List result = _validator.TestValidate(command); @@ -2314,7 +2316,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenAlbumCatalogNumberIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50))]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumbers: [new Faker().Random.String2(50)])]); // Act List result = _validator.TestValidate(command); @@ -2327,7 +2329,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalTitle: false))])]); // Act List result = _validator.TestValidate(command); @@ -2340,7 +2342,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))])]); // Act List result = _validator.TestValidate(command); @@ -2353,7 +2355,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeDescription: false))])]); // Act List result = _validator.TestValidate(command); @@ -2366,7 +2368,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))])]); // Act List result = _validator.TestValidate(command); @@ -2379,7 +2381,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2392,7 +2394,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2405,7 +2407,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))])]); // Act List result = _validator.TestValidate(command); @@ -2418,7 +2420,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2431,7 +2433,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))])]); // Act List result = _validator.TestValidate(command); @@ -2444,7 +2446,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2457,7 +2459,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))])]); // Act List result = _validator.TestValidate(command); @@ -2470,7 +2472,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackGenresAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); // Act List result = _validator.TestValidate(command); @@ -2485,7 +2487,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackTagsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); // Act List result = _validator.TestValidate(command); @@ -2500,7 +2502,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeLanguage: false))])]); // Act List result = _validator.TestValidate(command); @@ -2513,7 +2515,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); // Act List result = _validator.TestValidate(command); @@ -2526,7 +2528,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); // Act List result = _validator.TestValidate(command); @@ -2540,7 +2542,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2553,7 +2555,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); // Act List result = _validator.TestValidate(command); @@ -2566,7 +2568,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalLanguage: false))])]); // Act List result = _validator.TestValidate(command); @@ -2579,7 +2581,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); // Act List result = _validator.TestValidate(command); @@ -2592,7 +2594,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); // Act List result = _validator.TestValidate(command); @@ -2606,7 +2608,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); // Act List result = _validator.TestValidate(command); @@ -2619,7 +2621,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); // Act List result = _validator.TestValidate(command); @@ -2632,7 +2634,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackMusicBrainzIdsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), musicBrainzWorkId: Guid.NewGuid())])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.NewGuid()))])]); // Act List result = _validator.TestValidate(command); @@ -2658,7 +2660,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenDiscNumberIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2684,7 +2686,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackScriptIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2710,7 +2712,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackKeyIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2736,7 +2738,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackBpmIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2762,7 +2764,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackWorkIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2775,7 +2777,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackWorkIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(255))])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(255)))])]); // Act List result = _validator.TestValidate(command); @@ -2801,7 +2803,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackMoodsIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); @@ -2827,7 +2829,7 @@ public class UpdateArtistCommandValidatorTests public void Validate_WhenTrackIsrcsIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false)])]); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandlerTests.cs index 51d67bb7..bde4ff41 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandlerTests.cs @@ -78,7 +78,7 @@ public class GetArtistQueryHandlerTests Assert.False(result.IsFailure); Assert.Equal(artistId, result.Value.Id); Assert.Equal(libraryId, result.Value.LibraryId); - Assert.Equal(artist.Name, result.Value.Name); + Assert.Equal(artist.Name, result.Value.Metadata.Name); Assert.Equal(artist.Website, result.Value.Website); Assert.NotNull(result.Value.Albums); Assert.Equal(artist.Albums.Count, result.Value.Albums!.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandlerTests.cs index 1d398a19..276f74ba 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandlerTests.cs @@ -59,7 +59,7 @@ public class AddTrackCommandHandlerTests private readonly TrackEntityFixture _trackEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); @@ -369,7 +369,7 @@ public class AddTrackCommandHandlerTests public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); ArrangeArtist(command); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidatorTests.cs index 0c14b1e1..a2ac02de 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidatorTests.cs @@ -27,7 +27,8 @@ public class AddTrackCommandValidatorTests { private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); private readonly AddTrackCommandValidator _validator = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly TagDtoFixture _tagDtoFixture = new(); @@ -288,7 +289,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false)); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTitle: false)); // Act List result = _validator.TestValidate(command); @@ -301,7 +302,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(command); @@ -314,7 +315,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(command); @@ -328,7 +329,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(command); @@ -341,7 +342,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false)); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act List result = _validator.TestValidate(command); @@ -354,7 +355,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(command); @@ -367,7 +368,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act List result = _validator.TestValidate(command); @@ -380,7 +381,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false)); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeDescription: false)); // Act List result = _validator.TestValidate(command); @@ -393,7 +394,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); // Act List result = _validator.TestValidate(command); @@ -406,7 +407,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false)); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act List result = _validator.TestValidate(command); @@ -419,7 +420,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); // Act List result = _validator.TestValidate(command); @@ -432,7 +433,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); // Act List result = _validator.TestValidate(command); @@ -445,7 +446,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -458,7 +459,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); // Act List result = _validator.TestValidate(command); @@ -471,7 +472,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); // Act List result = _validator.TestValidate(command); @@ -484,7 +485,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -497,7 +498,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -510,7 +511,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); // Act List result = _validator.TestValidate(command); @@ -523,7 +524,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -536,7 +537,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -549,7 +550,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); // Act List result = _validator.TestValidate(command); @@ -562,7 +563,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); // Act List result = _validator.TestValidate(command); @@ -575,7 +576,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -588,7 +589,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(command); @@ -601,7 +602,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); // Act List result = _validator.TestValidate(command); @@ -614,7 +615,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); // Act List result = _validator.TestValidate(command); @@ -627,7 +628,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false)); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeGenres: false)); // Act List result = _validator.TestValidate(command); @@ -640,7 +641,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(command); @@ -653,7 +654,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(command); @@ -666,7 +667,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(command); @@ -681,7 +682,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false)); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTags: false)); // Act List result = _validator.TestValidate(command); @@ -694,7 +695,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(command); @@ -707,7 +708,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(command); @@ -720,7 +721,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(command); @@ -735,7 +736,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false)); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeLanguage: false)); // Act List result = _validator.TestValidate(command); @@ -748,7 +749,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -761,7 +762,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(command); @@ -774,7 +775,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenLanguageCodeIsValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); // Act List result = _validator.TestValidate(command); @@ -787,7 +788,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -800,7 +801,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -813,7 +814,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(command); @@ -826,7 +827,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -839,7 +840,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false)); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act List result = _validator.TestValidate(command); @@ -852,7 +853,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -865,7 +866,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(command); @@ -878,7 +879,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -891,7 +892,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -904,7 +905,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(command); @@ -917,7 +918,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -943,7 +944,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenMusicBrainzRecordingIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -969,7 +970,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty); + AddTrackCommand command = _addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.Empty)); // Act List result = _validator.TestValidate(command); @@ -985,7 +986,7 @@ public class AddTrackCommandValidatorTests AddTrackCommand command = _addTrackCommandFixture.Create( musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), - musicBrainzWorkId: Guid.NewGuid()); + work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.NewGuid())); // Act List result = _validator.TestValidate(command); @@ -1054,7 +1055,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenDiscNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1093,7 +1094,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenScriptIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1132,7 +1133,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenKeyIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1173,7 +1174,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenBpmIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1199,7 +1200,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenWorkExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(work: new Faker().Random.String2(256)); + AddTrackCommand command = _addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(256))); // Act List result = _validator.TestValidate(command); @@ -1212,7 +1213,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenWorkIsNull_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + AddTrackCommand command = _addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1225,7 +1226,7 @@ public class AddTrackCommandValidatorTests public void Validate_WhenWorkIsValid_ShouldNotHaveValidationError() { // Arrange - AddTrackCommand command = _addTrackCommandFixture.Create(work: new Faker().Random.String2(255)); + AddTrackCommand command = _addTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(255))); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs index fe9bb86e..a470115e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs @@ -12,6 +12,8 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; @@ -60,9 +62,11 @@ public class UpdateTrackCommandHandlerTests private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly TrackEntityFixture _trackEntityFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -102,14 +106,7 @@ public class UpdateTrackCommandHandlerTests .Returns(callInfo => { IReadOnlyCollection contributorIds = callInfo.Arg>(); - return Result.From>([.. contributorIds.Select(contributorId => new MediaContributorEntity - { - Id = contributorId, - DisplayName = contributorId.ToString(), - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - })]); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); }); _sut = new UpdateTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); @@ -471,7 +468,7 @@ public class UpdateTrackCommandHandlerTests Guid albumId = Guid.NewGuid(); Guid trackId = Guid.NewGuid(); AlbumEntity invalidAlbum = _albumEntityFixture.Create(id: albumId, libraryId: libraryId, tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]); - invalidAlbum.Genres = [new GenreEntity(string.Empty)]; + invalidAlbum.Genres = [_genreEntityFixture.Create(name: string.Empty)]; ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: libraryId, albums: [invalidAlbum]); UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString()); _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -492,7 +489,7 @@ public class UpdateTrackCommandHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); - AudioMetadataDto invalidMetadata = _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]); + MusicTrackMetadataDto invalidMetadata = _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]); UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), metadata: invalidMetadata); _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(existingArtist)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs index 5af646ad..b0bfe69a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs @@ -30,7 +30,8 @@ public class UpdateTrackCommandValidatorTests { private readonly UpdateTrackCommandFixture _updateTrackCommandFixture = new(); private readonly UpdateTrackCommandValidator _validator = new(); - private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new(); + private readonly MusicWorkDtoFixture _musicWorkDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly TagDtoFixture _tagDtoFixture = new(); @@ -434,7 +435,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTitle: false)); // Act List result = _validator.TestValidate(command); @@ -447,7 +448,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTitleIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: string.Empty)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: string.Empty)); // Act List result = _validator.TestValidate(command); @@ -460,7 +461,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTitleIsWhitespace_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: " ")); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: " ")); // Act List result = _validator.TestValidate(command); @@ -473,7 +474,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(256))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(256))); // Act List result = _validator.TestValidate(command); @@ -486,7 +487,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTitleIs255Characters_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(255))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: new Faker().Random.String2(255))); // Act List result = _validator.TestValidate(command); @@ -499,7 +500,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(256))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(256))); // Act List result = _validator.TestValidate(command); @@ -512,7 +513,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalTitleIs255Characters_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(255))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(255))); // Act List result = _validator.TestValidate(command); @@ -525,7 +526,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act List result = _validator.TestValidate(command); @@ -538,7 +539,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act List result = _validator.TestValidate(command); @@ -551,7 +552,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenDescriptionIs2000Characters_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2000))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(description: new Faker().Random.String2(2000))); // Act List result = _validator.TestValidate(command); @@ -564,7 +565,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeDescription: false)); // Act List result = _validator.TestValidate(command); @@ -577,7 +578,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act List result = _validator.TestValidate(command); @@ -590,7 +591,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsZero_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 0, includeReReleaseDate: false, includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 0, includeReReleaseDate: false, includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -603,7 +604,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 10000, includeReReleaseDate: false, includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 10000, includeReReleaseDate: false, includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -616,7 +617,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -629,7 +630,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -642,7 +643,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsZero_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, reReleaseYear: 0))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, reReleaseYear: 0))); // Act List result = _validator.TestValidate(command); @@ -655,7 +656,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, reReleaseYear: 10000))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, reReleaseYear: 10000))); // Act List result = _validator.TestValidate(command); @@ -668,7 +669,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, reReleaseYear: 2001))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, reReleaseYear: 2001))); // Act List result = _validator.TestValidate(command); @@ -681,7 +682,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -694,7 +695,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -707,7 +708,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReleaseVersionIs50Characters_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); // Act List result = _validator.TestValidate(command); @@ -720,7 +721,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReleaseVersionIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); // Act List result = _validator.TestValidate(command); @@ -733,7 +734,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2021, includeReReleaseDate: false, includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2021, includeReReleaseDate: false, includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -746,7 +747,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false, includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false, includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -759,7 +760,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, reReleaseDate: new DateOnly(2020, 1, 1), reReleaseYear: 2021))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, reReleaseDate: new DateOnly(2020, 1, 1), reReleaseYear: 2021))); // Act List result = _validator.TestValidate(command); @@ -772,7 +773,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseDateAndYearMatch_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, reReleaseDate: new DateOnly(2020, 1, 1), reReleaseYear: 2020))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, reReleaseDate: new DateOnly(2020, 1, 1), reReleaseYear: 2020))); // Act List result = _validator.TestValidate(command); @@ -785,7 +786,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2001, includeReReleaseDate: false, reReleaseYear: 2000))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2001, includeReReleaseDate: false, reReleaseYear: 2000))); // Act List result = _validator.TestValidate(command); @@ -798,7 +799,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, reReleaseYear: 2001))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, reReleaseYear: 2001))); // Act List result = _validator.TestValidate(command); @@ -811,7 +812,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), includeOriginalReleaseYear: false, reReleaseDate: new DateOnly(2000, 1, 1), includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), includeOriginalReleaseYear: false, reReleaseDate: new DateOnly(2000, 1, 1), includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -824,7 +825,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), includeOriginalReleaseYear: false, reReleaseDate: new DateOnly(2001, 1, 1), includeReReleaseYear: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), includeOriginalReleaseYear: false, reReleaseDate: new DateOnly(2001, 1, 1), includeReReleaseYear: false))); // Act List result = _validator.TestValidate(command); @@ -837,7 +838,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeGenres: false)); // Act List result = _validator.TestValidate(command); @@ -850,7 +851,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(command); @@ -863,7 +864,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(command); @@ -876,7 +877,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(command); @@ -889,7 +890,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeTags: false)); // Act List result = _validator.TestValidate(command); @@ -902,7 +903,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(command); @@ -915,7 +916,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(command); @@ -928,7 +929,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(command); @@ -941,7 +942,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeLanguage: false)); // Act List result = _validator.TestValidate(command); @@ -954,7 +955,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -967,7 +968,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); // Act List result = _validator.TestValidate(command); @@ -980,7 +981,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(command); @@ -993,7 +994,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -1006,7 +1007,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -1019,7 +1020,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(command); @@ -1032,7 +1033,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -1045,7 +1046,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act List result = _validator.TestValidate(command); @@ -1058,7 +1059,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -1071,7 +1072,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); // Act List result = _validator.TestValidate(command); @@ -1084,7 +1085,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(command); @@ -1097,7 +1098,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(command); @@ -1110,7 +1111,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -1123,7 +1124,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(command); @@ -1136,7 +1137,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(command); @@ -1175,7 +1176,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenMusicBrainzRecordingIdIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1214,7 +1215,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenMusicBrainzTrackIdIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1227,7 +1228,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.Empty)); // Act List result = _validator.TestValidate(command); @@ -1240,7 +1241,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenMusicBrainzWorkIdIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(musicBrainzWorkId: Guid.NewGuid()); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(musicBrainzWorkId: Guid.NewGuid())); // Act List result = _validator.TestValidate(command); @@ -1253,7 +1254,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenMusicBrainzWorkIdIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1357,7 +1358,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenDiscNumberIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1396,7 +1397,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenScriptIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1435,7 +1436,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenKeyIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1487,7 +1488,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenBpmIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); @@ -1500,7 +1501,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenWorkExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(work: new Faker().Random.String2(256)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(256))); // Act List result = _validator.TestValidate(command); @@ -1513,7 +1514,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenWorkIs255Characters_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(work: new Faker().Random.String2(255)); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(work: _musicWorkDtoFixture.Create(title: new Faker().Random.String2(255))); // Act List result = _validator.TestValidate(command); @@ -1526,7 +1527,7 @@ public class UpdateTrackCommandValidatorTests public void Validate_WhenWorkIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMoods: false, includeIsrcs: false); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs index 153e4fe7..79f310a7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs @@ -3,24 +3,30 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management; using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -42,10 +48,14 @@ public class AddLibraryCommandHandlerTests private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly IEnvironmentContext _mockEnvironmentContext; private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; + private readonly ILibraryPathTemplateService _mockLibraryPathTemplateService; private readonly IValidator _mockValidator; private readonly AddLibraryCommandHandler _sut; private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); private readonly Guid _userId; /// @@ -62,6 +72,7 @@ public class AddLibraryCommandHandlerTests _mockDomainEventsQueue = Substitute.For(); _mockEnvironmentContext = Substitute.For(); _mockProviderConfigurationStore = Substitute.For(); + _mockLibraryPathTemplateService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); @@ -75,8 +86,9 @@ public class AddLibraryCommandHandlerTests _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty())); - _sut = new AddLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); + _sut = new AddLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockLibraryPathTemplateService, _mockUnitOfWork, _mockValidator); } [Fact] @@ -290,4 +302,118 @@ public class AddLibraryCommandHandlerTests await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenPathTemplatePartsIsNull_ShouldResolveTemplateWithoutParts() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: null); + LibraryPathPart defaultPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: true); + LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [defaultPart]); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(defaultTemplate)); + LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(persistedLibrary)); + LibraryType expectedLibraryType = Enum.Parse(command.LibraryType!); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockLibraryPathTemplateService.Received(1).ResolveTemplate( + expectedLibraryType, + Arg.Is>(parts => parts.Count == 0)); + await _mockLibraryRepository.Received(1).InsertAsync( + Arg.Is(library => + library.PathTemplateParts.Count == 1 && + library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist && + library.PathTemplateParts.First().Representation == "{0}" && + library.PathTemplateParts.First().IsOptional), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPathTemplatePartsAreProvided_ShouldBuildTemplateFromProvidedParts() + { + // Arrange + LibraryPathTemplatePartDto providedDto = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}", + isOptional: false); + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [providedDto]); + LibraryPathPart providedPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: false); + LibraryPathTemplate resolvedTemplate = _libraryPathTemplateFixture.Create(parts: [providedPart]); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(resolvedTemplate)); + LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(persistedLibrary)); + LibraryType expectedLibraryType = Enum.Parse(command.LibraryType!); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockLibraryPathTemplateService.Received(1).ResolveTemplate( + expectedLibraryType, + Arg.Is>(parts => + parts.Count == 1 && + parts[0].Kind == LibraryPathPartKind.Artist && + parts[0].Representation == "{0}" && + !parts[0].IsOptional)); + await _mockLibraryRepository.Received(1).InsertAsync( + Arg.Is(library => + library.PathTemplateParts.Count == 1 && + library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist && + library.PathTemplateParts.First().Representation == "{0}" && + !library.PathTemplateParts.First().IsOptional), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPathTemplateMappingFails_ShouldReturnErrorWithoutPersisting() + { + // Arrange + LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" }; + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError); + _mockLibraryPathTemplateService.DidNotReceive().ResolveTemplate(Arg.Any(), Arg.Any>()); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPathTemplateValidationFails_ShouldReturnErrorWithoutPersisting() + { + // Arrange + LibraryPathTemplatePartDto validPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}"); + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [validPart]); + Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType; + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(validationError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(validationError, result.FirstError); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs index cde654eb..afb9cced 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management; using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -18,6 +21,7 @@ public class AddLibraryCommandValidatorTests { private readonly AddLibraryCommandValidator _validator = new(); private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new(); + private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); [Fact] public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() @@ -201,6 +205,92 @@ public class AddLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.TitleMustBeMaximum255CharactersLong); } + [Fact] + public void Validate_WhenPathTemplatePartsIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType); + result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // an absent kind + [InlineData("")] // an empty kind + [InlineData(" ")] // a whitespace kind + public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind) + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = kind }; + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType); + } + + [Theory] + [InlineData(null)] // an absent representation + [InlineData("")] // an empty representation + [InlineData(" ")] // a whitespace representation + public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation) + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: nameof(LibraryPathPartKind.Artist)) with { Representation = representation }; + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty); + } + + [Fact] + public void Validate_WhenSeparatorPartRepresentationIsEmpty_ShouldNotHaveValidationError() + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Separator), + representation: string.Empty); + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPathTemplatePartsAreValid_ShouldNotHaveValidationError() + { + // Arrange + LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Literal), + representation: "Various Artists"); + LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Separator), + representation: string.Empty); + LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}"); + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [literalPart, separatorPart, typedPart]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + [Fact] public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs index 942f528f..047693d4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -10,12 +11,16 @@ using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management; using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; @@ -23,6 +28,7 @@ using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -44,10 +50,14 @@ public class UpdateLibraryCommandHandlerTests private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly IEnvironmentContext _mockEnvironmentContext; private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; + private readonly ILibraryPathTemplateService _mockLibraryPathTemplateService; private readonly IValidator _mockValidator; private readonly UpdateLibraryCommandHandler _sut; private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); private readonly Guid _userId; /// @@ -64,6 +74,7 @@ public class UpdateLibraryCommandHandlerTests _mockDomainEventsQueue = Substitute.For(); _mockEnvironmentContext = Substitute.For(); _mockProviderConfigurationStore = Substitute.For(); + _mockLibraryPathTemplateService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); @@ -78,8 +89,9 @@ public class UpdateLibraryCommandHandlerTests _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty())); - _sut = new UpdateLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); + _sut = new UpdateLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockLibraryPathTemplateService, _mockUnitOfWork, _mockValidator); } [Fact] @@ -416,4 +428,124 @@ public class UpdateLibraryCommandHandlerTests await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenPathTemplatePartsIsNull_ShouldResolveTemplateWithoutParts() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + LibraryPathPart defaultPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: true); + LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [defaultPart]); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(defaultTemplate)); + LibraryType expectedLibraryType = Enum.Parse(command.LibraryType!); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockLibraryPathTemplateService.Received(1).ResolveTemplate( + expectedLibraryType, + Arg.Is>(parts => parts.Count == 0)); + await _mockLibraryRepository.Received(1).UpdateAsync( + Arg.Is(library => + library.PathTemplateParts.Count == 1 && + library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist && + library.PathTemplateParts.First().Representation == "{0}" && + library.PathTemplateParts.First().IsOptional), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPathTemplatePartsAreProvided_ShouldBuildTemplateFromProvidedParts() + { + // Arrange + LibraryPathTemplatePartDto providedDto = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}", + isOptional: false); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [providedDto]); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + LibraryPathPart providedPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: false); + LibraryPathTemplate resolvedTemplate = _libraryPathTemplateFixture.Create(parts: [providedPart]); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(resolvedTemplate)); + LibraryType expectedLibraryType = Enum.Parse(command.LibraryType!); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockLibraryPathTemplateService.Received(1).ResolveTemplate( + expectedLibraryType, + Arg.Is>(parts => + parts.Count == 1 && + parts[0].Kind == LibraryPathPartKind.Artist && + parts[0].Representation == "{0}" && + !parts[0].IsOptional)); + await _mockLibraryRepository.Received(1).UpdateAsync( + Arg.Is(library => + library.PathTemplateParts.Count == 1 && + library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist && + library.PathTemplateParts.First().Representation == "{0}" && + !library.PathTemplateParts.First().IsOptional), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPathTemplateMappingFails_ShouldReturnErrorWithoutPersisting() + { + // Arrange + LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" }; + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError); + _mockLibraryPathTemplateService.DidNotReceive().ResolveTemplate(Arg.Any(), Arg.Any>()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPathTemplateValidationFails_ShouldReturnErrorWithoutPersisting() + { + // Arrange + LibraryPathTemplatePartDto validPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}"); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [validPart]); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType; + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(validationError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(validationError, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs index f5c025a2..6f77cf71 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management; using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -19,6 +22,7 @@ public class UpdateLibraryCommandValidatorTests { private readonly UpdateLibraryCommandValidator _validator = new(); private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new(); + private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); [Fact] public void Validate_WhenIdIsEmpty_ShouldHaveValidationError() @@ -256,6 +260,92 @@ public class UpdateLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.TitleMustBeMaximum255CharactersLong); } + [Fact] + public void Validate_WhenPathTemplatePartsIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType); + result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // an absent kind + [InlineData("")] // an empty kind + [InlineData(" ")] // a whitespace kind + public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind) + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = kind }; + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType); + } + + [Theory] + [InlineData(null)] // an absent representation + [InlineData("")] // an empty representation + [InlineData(" ")] // a whitespace representation + public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation) + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: nameof(LibraryPathPartKind.Artist)) with { Representation = representation }; + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty); + } + + [Fact] + public void Validate_WhenSeparatorPartRepresentationIsEmpty_ShouldNotHaveValidationError() + { + // Arrange + LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Separator), + representation: string.Empty); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPathTemplatePartsAreValid_ShouldNotHaveValidationError() + { + // Arrange + LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Literal), + representation: "Various Artists"); + LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Separator), + representation: string.Empty); + LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create( + kind: nameof(LibraryPathPartKind.Artist), + representation: "{0}"); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [literalPart, separatorPart, typedPart]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + [Fact] public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs new file mode 100644 index 00000000..c054f80b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs @@ -0,0 +1,179 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.Management.Deletion; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Deletion; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksMediaLibraryItemDeletionStrategyTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IBookArtworkService _mockBookArtworkService; + private readonly ILogger _mockLogger; + private readonly BooksMediaLibraryItemDeletionStrategy _sut; + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BooksMediaLibraryItemDeletionStrategyTests() + { + _mockUnitOfWork = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + + _mockBookArtworkService = Substitute.For(); + _mockLogger = Substitute.For>(); + + _sut = new BooksMediaLibraryItemDeletionStrategy(_mockUnitOfWork, _mockBookArtworkService, _mockLogger); + } + + [Fact] + public async Task DeleteItemAsync_WhenBookExistsAtPath_ShouldDeleteTheBookAndItsArtwork() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); + _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, book.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + _mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title); + await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenNoBookExistsAtPath_ShouldDoNothing() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); + _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork")); + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, book.Path, CancellationToken.None); + + // Assert + // a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged + Assert.True(result.IsSuccess); + await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenGetBookFails_ShouldReturnFailure() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the book"); + _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenDeleteBookFails_ShouldReturnFailure() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); + _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + Error error = Error.Failure("Database.Error", "Failed to delete the book"); + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, book.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs new file mode 100644 index 00000000..8a96de2f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs @@ -0,0 +1,329 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.Management.Deletion; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Deletion; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMediaLibraryItemDeletionStrategyTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ITrackRepository _mockTrackRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IArtistRepository _mockArtistRepository; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly MusicMediaLibraryItemDeletionStrategy _sut; + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicMediaLibraryItemDeletionStrategyTests() + { + _mockUnitOfWork = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + + _sut = new MusicMediaLibraryItemDeletionStrategy(_mockUnitOfWork); + } + + [Fact] + public async Task DeleteItemAsync_WhenAlbumHasOtherTracks_ShouldDeleteOnlyTheTrackAndItsArtwork() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false); + TrackEntity otherTrack = _trackEntityFixture.Create(albumId: albumId); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([otherTrack])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()); + await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Album, Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenAlbumHasNoOtherTracksButArtistHasOtherAlbums_ShouldDeleteTheAlbumAndItsArtwork() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false); + AlbumEntity otherAlbum = _albumEntityFixture.Create(artistId: artistId, includeTracks: false); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>([otherAlbum])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()); + await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenAlbumAndArtistAreLeftWithNoChildren_ShouldDeleteTheTrackAlbumAndArtist() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>([album])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()); + await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any()); + await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any()); + await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenNoTrackExistsAtPath_ShouldDoNothing() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + _mockTrackRepository.GetByPathAsync(libraryId.Value, "/music/deleted.flac", Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, "/music/deleted.flac", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenGetTrackFails_ShouldReturnFailure() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the track"); + _mockTrackRepository.GetByPathAsync(libraryId.Value, "/music/deleted.flac", Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, "/music/deleted.flac", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenDeleteTrackArtworkFails_ShouldReturnFailure() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + Error error = Error.Failure("Database.Error", "Failed to delete the track artwork"); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenDeleteAlbumArtworkFails_ShouldReturnFailure() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false); + Error error = Error.Failure("Database.Error", "Failed to delete the album artwork"); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenDeleteArtistArtworkFails_ShouldReturnFailure() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false); + Error error = Error.Failure("Database.Error", "Failed to delete the artist artwork"); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>([album])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs index 18d28223..644b8b6f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs @@ -1,23 +1,20 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.Management.Deletion; using Lumina.Application.Core.MediaLibrary.Management.Events; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.Extensions.Logging; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -32,13 +29,11 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; public class LibraryMediaItemDeletedDomainEventHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; - private readonly IBookRepository _mockBookRepository; private readonly ILibraryRepository _mockLibraryRepository; - private readonly IBookArtworkService _mockBookArtworkService; + private readonly IMediaLibraryItemDeletionStrategy _mockDeletionStrategy; private readonly ILogger _mockLogger; private readonly LibraryMediaItemDeletedDomainEventHandler _sut; private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly BookEntityFixture _bookEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new(); @@ -48,54 +43,26 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests public LibraryMediaItemDeletedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); - _mockBookRepository = Substitute.For(); _mockLibraryRepository = Substitute.For(); - _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); - _mockBookArtworkService = Substitute.For(); + _mockDeletionStrategy = Substitute.For(); _mockLogger = Substitute.For>(); - _sut = new LibraryMediaItemDeletedDomainEventHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger); + _sut = new LibraryMediaItemDeletedDomainEventHandler(_mockUnitOfWork, [_mockDeletionStrategy], _mockLogger); } [Fact] - public async Task HandleAsync_WhenBookExistsAtPath_ShouldDeleteTheBookAndItsArtwork() + public async Task HandleAsync_WhenDeletionStrategyExistsForTheLibraryType_ShouldDelegateToIt() { // Arrange LibraryId libraryId = _libraryIdFixture.Create(); - BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); - LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); - _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) - .Returns(Result.From(book)); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, libraryType: LibraryType.Book); _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) - .Returns(Result.From(Result.Deleted)); - _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); - - // Act - await _sut.HandleAsync(domainEvent, CancellationToken.None); - - // Assert - _mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title); - await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenNoBookExistsAtPath_ShouldDoNothing() - { - // Arrange - LibraryId libraryId = _libraryIdFixture.Create(); - _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) - .Returns(Result.From(null)); + _mockDeletionStrategy.SupportedLibraryType.Returns(LibraryType.Book); + _mockDeletionStrategy.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) + .Returns(Result.Success); LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub"); @@ -103,48 +70,35 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDeletionStrategy.Received(1).DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()); } [Fact] - public async Task HandleAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook() + public async Task HandleAsync_WhenNoDeletionStrategyExistsForTheLibraryType_ShouldNotDelete() { // Arrange LibraryId libraryId = _libraryIdFixture.Create(); - BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); - LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); - _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) - .Returns(Result.From(book)); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, libraryType: LibraryType.Music); _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork")); - _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) - .Returns(Result.From(Result.Deleted)); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockDeletionStrategy.SupportedLibraryType.Returns(LibraryType.Book); - LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/music/deleted.flac"); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - // a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged - await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] - public async Task HandleAsync_WhenGetBookFails_ShouldThrowEventualConsistencyException() + public async Task HandleAsync_WhenGetLibraryFails_ShouldThrowEventualConsistencyException() { // Arrange LibraryId libraryId = _libraryIdFixture.Create(); - Error error = Error.Failure("Database.Error", "Failed to get the book"); - _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) + Error error = Error.Failure("Database.Error", "Failed to get the library"); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(error); LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub"); @@ -155,29 +109,39 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] - public async Task HandleAsync_WhenDeleteBookFails_ShouldThrowEventualConsistencyException() + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldThrowEventualConsistencyException() { // Arrange LibraryId libraryId = _libraryIdFixture.Create(); - BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); - LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); - _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) - .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub"); + + // Act & Assert + await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletionFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, libraryType: LibraryType.Book); + Error error = Error.Failure("Database.Error", "Failed to delete the item"); _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - Error error = Error.Failure("Database.Error", "Failed to delete the book"); - _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) + _mockDeletionStrategy.SupportedLibraryType.Returns(LibraryType.Book); + _mockDeletionStrategy.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) .Returns(error); - LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub"); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( @@ -185,6 +149,5 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs index fc3f6920..6f07c006 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs @@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; @@ -35,6 +36,7 @@ public class GetLibrariesQueryHandlerTests private readonly GetLibrariesQueryHandler _sut; private readonly GetLibrariesQueryFixture _getLibrariesQueryFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly Guid _userId; /// @@ -66,7 +68,7 @@ public class GetLibrariesQueryHandlerTests _libraryEntityFixture.Create(userId: _userId), _libraryEntityFixture.Create(userId: Guid.NewGuid()) ]; - _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = libraries, CurrentPage = 1, PerPage = libraries.Count, Count = libraries.Count, NumberOfPages = 1 })); + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: libraries, currentPage: 1, perPage: libraries.Count, count: libraries.Count, numberOfPages: 1))); // Act Result result = await _sut.HandleAsync(_getLibrariesQueryFixture.Create(), CancellationToken.None); @@ -88,7 +90,7 @@ public class GetLibrariesQueryHandlerTests _libraryEntityFixture.Create(userId: _userId), _libraryEntityFixture.Create(userId: otherUserId) ]; - _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = libraries, CurrentPage = 1, PerPage = libraries.Count, Count = libraries.Count, NumberOfPages = 1 })); + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: libraries, currentPage: 1, perPage: libraries.Count, count: libraries.Count, numberOfPages: 1))); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs new file mode 100644 index 00000000..32394ae0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs @@ -0,0 +1,169 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsQueryHandlerTests +{ + private readonly ILibraryPathPartCatalog _mockBookCatalog; + private readonly ILibraryPathPartCatalog _mockMusicCatalog; + private readonly GetLibraryPathTemplatePartsQueryHandler _sut; + private readonly GetLibraryPathTemplatePartsQueryFixture _getLibraryPathTemplatePartsQueryFixture = new(); + private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new(); + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryPathTemplatePartsQueryHandlerTests() + { + _mockBookCatalog = Substitute.For(); + _mockBookCatalog.SupportedLibraryType.Returns(LibraryType.Book); + _mockBookCatalog.GetPartDefinitions().Returns([]); + _mockBookCatalog.GetDefaultTemplate().Returns(LibraryPathTemplate.Empty()); + _mockMusicCatalog = Substitute.For(); + _mockMusicCatalog.SupportedLibraryType.Returns(LibraryType.Music); + _mockMusicCatalog.GetPartDefinitions().Returns([]); + _mockMusicCatalog.GetDefaultTemplate().Returns(LibraryPathTemplate.Empty()); + + _sut = new GetLibraryPathTemplatePartsQueryHandler([_mockBookCatalog, _mockMusicCatalog]); + } + + [Theory] + [InlineData("")] // an absent library type + [InlineData(" ")] // a whitespace library type + [InlineData("NotARealLibraryType")] // an unknown library type + public async Task HandleAsync_WhenLibraryTypeIsUnknownOrAbsent_ShouldReturnUnknownLibraryTypeError(string libraryType) + { + // Arrange + GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: libraryType); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.UnknownLibraryType, result.FirstError); + _ = _mockBookCatalog.DidNotReceive().SupportedLibraryType; + _ = _mockMusicCatalog.DidNotReceive().SupportedLibraryType; + } + + [Fact] + public async Task HandleAsync_WhenNoCatalogSupportsLibraryType_ShouldReturnEmptyPartsAndDefaultTemplateParts() + { + // Arrange + GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: nameof(LibraryType.Photo)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Parts); + Assert.Empty(result.Value.DefaultTemplateParts); + _ = _mockBookCatalog.Received(1).SupportedLibraryType; + _ = _mockMusicCatalog.Received(1).SupportedLibraryType; + _mockBookCatalog.DidNotReceive().GetPartDefinitions(); + _mockBookCatalog.DidNotReceive().GetDefaultTemplate(); + _mockMusicCatalog.DidNotReceive().GetPartDefinitions(); + _mockMusicCatalog.DidNotReceive().GetDefaultTemplate(); + } + + [Fact] + public async Task HandleAsync_WhenCatalogSupportsLibraryType_ShouldMapPartDefinitionsAndDefaultTemplatePartsInOrder() + { + // Arrange + List partDefinitions = + [ + _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.Artist, + valueType: LibraryPathValueType.Text, + defaultRepresentation: "{0}", + isOptionalByDefault: false), + _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.TrackNumber, + valueType: LibraryPathValueType.Integer, + defaultRepresentation: "{0:00}", + isOptionalByDefault: true), + _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.ReleaseYear, + valueType: LibraryPathValueType.Year, + defaultRepresentation: "{0}", + isOptionalByDefault: false) + ]; + _mockMusicCatalog.GetPartDefinitions().Returns(partDefinitions); + + LibraryPathPart artistPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: false); + LibraryPathPart separatorPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Separator, + representation: string.Empty, + isOptional: false); + LibraryPathPart trackNamePart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.TrackName, + representation: "{0}", + isOptional: true); + LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [artistPart, separatorPart, trackNamePart]); + _mockMusicCatalog.GetDefaultTemplate().Returns(defaultTemplate); + + GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: nameof(LibraryType.Music)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(3, result.Value.Parts.Count); + Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.Value.Parts[0].Kind); + Assert.Equal(LibraryPathValueType.Text.ToString(), result.Value.Parts[0].ValueType); + Assert.Equal("{0}", result.Value.Parts[0].DefaultRepresentation); + Assert.False(result.Value.Parts[0].IsOptionalByDefault); + Assert.Equal(LibraryPathPartKind.TrackNumber.ToString(), result.Value.Parts[1].Kind); + Assert.Equal(LibraryPathValueType.Integer.ToString(), result.Value.Parts[1].ValueType); + Assert.Equal("{0:00}", result.Value.Parts[1].DefaultRepresentation); + Assert.True(result.Value.Parts[1].IsOptionalByDefault); + Assert.Equal(LibraryPathPartKind.ReleaseYear.ToString(), result.Value.Parts[2].Kind); + Assert.Equal(LibraryPathValueType.Year.ToString(), result.Value.Parts[2].ValueType); + Assert.Equal("{0}", result.Value.Parts[2].DefaultRepresentation); + Assert.False(result.Value.Parts[2].IsOptionalByDefault); + + Assert.Equal(3, result.Value.DefaultTemplateParts.Count); + Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.Value.DefaultTemplateParts[0].Kind); + Assert.Equal("{0}", result.Value.DefaultTemplateParts[0].Representation); + Assert.False(result.Value.DefaultTemplateParts[0].IsOptional); + Assert.Equal(LibraryPathPartKind.Separator.ToString(), result.Value.DefaultTemplateParts[1].Kind); + Assert.Equal(string.Empty, result.Value.DefaultTemplateParts[1].Representation); + Assert.False(result.Value.DefaultTemplateParts[1].IsOptional); + Assert.Equal(LibraryPathPartKind.TrackName.ToString(), result.Value.DefaultTemplateParts[2].Kind); + Assert.Equal("{0}", result.Value.DefaultTemplateParts[2].Representation); + Assert.True(result.Value.DefaultTemplateParts[2].IsOptional); + + _mockMusicCatalog.Received(1).GetPartDefinitions(); + _mockMusicCatalog.Received(1).GetDefaultTemplate(); + _mockBookCatalog.DidNotReceive().GetPartDefinitions(); + _mockBookCatalog.DidNotReceive().GetDefaultTemplate(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index f2c3dfa9..5342c062 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -57,7 +57,7 @@ public class AddBookCommandHandlerTests private readonly IPathService _mockPathService; private readonly Guid _userId; private readonly AddBookCommandHandler _sut; - private readonly AddBookCommandFixture _commandBookFixture = new(); + private readonly AddBookCommandFixture _addBookCommandFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); @@ -65,6 +65,7 @@ public class AddBookCommandHandlerTests private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// @@ -104,14 +105,7 @@ public class AddBookCommandHandlerTests .Returns(callInfo => { IReadOnlyCollection contributorIds = callInfo.Arg>(); - return Result.From>([.. contributorIds.Select(contributorId => new MediaContributorEntity - { - Id = contributorId, - DisplayName = contributorId.ToString(), - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - })]); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); }); IValidator mockValidator = Substitute.For>(); @@ -125,7 +119,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); _mockValidator.Validate(Arg.Any()) .Returns([Errors.WrittenContent.IsbnListCannotBeNull]); @@ -144,7 +138,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); BookEntity? insertedEntity = null; _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) @@ -170,7 +164,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenRepositoryInsertFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Errors.WrittenContent.BookAlreadyExists); @@ -189,7 +183,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenSaveChangesDetectsAConcurrentDuplicatePath_ShouldReturnThePersistenceError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) @@ -209,7 +203,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -226,7 +220,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -243,7 +237,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -260,7 +254,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")])); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")])); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -277,7 +271,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create( + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create( originalReleaseDate: new DateOnly(2025, 1, 1), originalReleaseYear: 2025, reReleaseDate: new DateOnly(2024, 1, 1), @@ -300,7 +294,7 @@ public class AddBookCommandHandlerTests // Arrange Guid firstContributorId = Guid.NewGuid(); Guid secondContributorId = Guid.NewGuid(); - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: + AddBookCommand bookCommand = _addBookCommandFixture.Create(contributors: [ _mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author), _mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Illustrator) @@ -333,7 +327,7 @@ public class AddBookCommandHandlerTests { // Arrange Guid contributorId = Guid.NewGuid(); - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: + AddBookCommand bookCommand = _addBookCommandFixture.Create(contributors: [ _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), @@ -366,7 +360,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); _mockCurrentUserService.UserId.Returns((Guid?)null); // Act @@ -383,7 +377,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -403,7 +397,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnFailureResultWithoutPersisting() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(_ => Result.From(null)); @@ -421,7 +415,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenBookPathIsNotWithinTheLibraryContentLocations_ShouldReturnFailureResultWithoutPersisting() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) .Returns(false); @@ -439,7 +433,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>([])); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index 49af0de5..6d447106 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; @@ -26,7 +26,7 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.B [ExcludeFromCodeCoverage] public class AddBookCommandValidatorTests { - private readonly AddBookCommandFixture _commandBookFixture = new(); + private readonly AddBookCommandFixture _addBookCommandFixture = new(); private readonly AddBookCommandValidator _validator = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); @@ -41,7 +41,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPathIsLongerThan2048Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub"); // Act List result = _validator.TestValidate(bookCommand); @@ -54,7 +54,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -67,7 +67,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(bookCommand); @@ -80,7 +80,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(bookCommand); @@ -93,7 +93,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(bookCommand); @@ -106,7 +106,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(bookCommand); @@ -119,7 +119,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -132,7 +132,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act List result = _validator.TestValidate(bookCommand); @@ -145,7 +145,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); // Act List result = _validator.TestValidate(bookCommand); @@ -158,7 +158,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -171,7 +171,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsEmpty_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: string.Empty)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: string.Empty)); // Act List result = _validator.TestValidate(bookCommand); @@ -184,7 +184,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -197,7 +197,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -210,7 +210,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); // Act List result = _validator.TestValidate(bookCommand); @@ -223,7 +223,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); // Act List result = _validator.TestValidate(bookCommand); @@ -236,7 +236,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -249,7 +249,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); // Act List result = _validator.TestValidate(bookCommand); @@ -262,7 +262,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); // Act List result = _validator.TestValidate(bookCommand); @@ -275,7 +275,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); // Act List result = _validator.TestValidate(bookCommand); @@ -288,7 +288,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -301,7 +301,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -314,7 +314,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -327,7 +327,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -340,7 +340,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -353,7 +353,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -366,7 +366,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(bookCommand); @@ -379,7 +379,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(bookCommand); @@ -392,7 +392,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(bookCommand); @@ -405,7 +405,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -418,7 +418,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(bookCommand); @@ -431,7 +431,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(bookCommand); @@ -444,7 +444,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(bookCommand); @@ -457,7 +457,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -470,7 +470,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -483,7 +483,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(bookCommand); @@ -496,7 +496,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -509,7 +509,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -522,7 +522,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -535,7 +535,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -548,7 +548,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -561,7 +561,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -574,7 +574,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -587,7 +587,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -600,7 +600,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(bookCommand); @@ -613,7 +613,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -626,7 +626,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -639,7 +639,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -652,7 +652,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -665,7 +665,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyPublisher_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -678,7 +678,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidPublisher_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); // Act List result = _validator.TestValidate(bookCommand); @@ -691,7 +691,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthPublisher_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(101))); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(101))); // Act List result = _validator.TestValidate(bookCommand); @@ -704,7 +704,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -717,7 +717,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsZero_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 0)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 0)); // Act List result = _validator.TestValidate(bookCommand); @@ -730,7 +730,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsNegative_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); // Act List result = _validator.TestValidate(bookCommand); @@ -743,7 +743,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsPositive_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); // Act List result = _validator.TestValidate(bookCommand); @@ -756,7 +756,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -769,7 +769,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(format: BookFormat.Hardcover); + AddBookCommand bookCommand = _addBookCommandFixture.Create(format: BookFormat.Hardcover); // Act List result = _validator.TestValidate(bookCommand); @@ -782,7 +782,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(format: (BookFormat)99); + AddBookCommand bookCommand = _addBookCommandFixture.Create(format: (BookFormat)99); // Act List result = _validator.TestValidate(bookCommand); @@ -795,7 +795,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -808,7 +808,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(50)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(edition: new Faker().Random.String2(50)); // Act List result = _validator.TestValidate(bookCommand); @@ -821,7 +821,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(51)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(edition: new Faker().Random.String2(51)); // Act List result = _validator.TestValidate(bookCommand); @@ -834,7 +834,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -847,7 +847,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsZero_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 0); + AddBookCommand bookCommand = _addBookCommandFixture.Create(volumeNumber: 0); // Act List result = _validator.TestValidate(bookCommand); @@ -860,7 +860,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: -1); + AddBookCommand bookCommand = _addBookCommandFixture.Create(volumeNumber: -1); // Act List result = _validator.TestValidate(bookCommand); @@ -873,7 +873,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsPositive_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 1); + AddBookCommand bookCommand = _addBookCommandFixture.Create(volumeNumber: 1); // Act List result = _validator.TestValidate(bookCommand); @@ -886,7 +886,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenSeriesIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); + AddBookCommand bookCommand = _addBookCommandFixture.Create(); // Act List result = _validator.TestValidate(bookCommand); @@ -899,7 +899,7 @@ public class AddBookCommandValidatorTests //public void Validate_WhenSeriesTitleIsEmpty_ShouldHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.Create(); + // var bookCommand = _addBookCommandFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = string.Empty } }; // // Act @@ -913,7 +913,7 @@ public class AddBookCommandValidatorTests //public void Validate_WhenSeriesTitleExceeds255Characters_ShouldHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.Create(); + // var bookCommand = _addBookCommandFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(256) } }; // // Act @@ -927,7 +927,7 @@ public class AddBookCommandValidatorTests //public void Validate_WhenSeriesTitleIsValid_ShouldNotHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.Create(); + // var bookCommand = _addBookCommandFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(200) } }; // // Act @@ -941,7 +941,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(10)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(asin: new Faker().Random.String2(10)); // Act List result = _validator.TestValidate(bookCommand); @@ -954,7 +954,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -967,7 +967,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(9)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(asin: new Faker().Random.String2(9)); // Act List result = _validator.TestValidate(bookCommand); @@ -980,7 +980,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -993,7 +993,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123456789"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(goodreadsId: "123456789"); // Act List result = _validator.TestValidate(bookCommand); @@ -1006,7 +1006,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "abc123"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(goodreadsId: "abc123"); // Act List result = _validator.TestValidate(bookCommand); @@ -1019,7 +1019,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpaces_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123 456"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(goodreadsId: "123 456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1032,7 +1032,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpecialCharacters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123-456"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(goodreadsId: "123-456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1045,7 +1045,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1058,7 +1058,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(lccn: "n78890351"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(lccn: "n78890351"); // Act List result = _validator.TestValidate(bookCommand); @@ -1071,7 +1071,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(lccn: "invalid123"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(lccn: "invalid123"); // Act List result = _validator.TestValidate(bookCommand); @@ -1084,7 +1084,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsTooLong_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(lccn: new Faker().Random.String2(15)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(lccn: new Faker().Random.String2(15)); // Act List result = _validator.TestValidate(bookCommand); @@ -1097,7 +1097,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsTooShort_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(lccn: "n12"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(lccn: "n12"); // Act List result = _validator.TestValidate(bookCommand); @@ -1110,7 +1110,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyOclcNumber_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1123,7 +1123,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat1_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocm12345678"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(oclcNumber: "ocm12345678"); // Act List result = _validator.TestValidate(bookCommand); @@ -1136,7 +1136,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat2_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocn123456789"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(oclcNumber: "ocn123456789"); // Act List result = _validator.TestValidate(bookCommand); @@ -1149,7 +1149,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat3_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "on1234567890"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(oclcNumber: "on1234567890"); // Act List result = _validator.TestValidate(bookCommand); @@ -1162,7 +1162,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat4_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "(OCoLC)1234567890"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(oclcNumber: "(OCoLC)1234567890"); // Act List result = _validator.TestValidate(bookCommand); @@ -1175,7 +1175,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat5_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "12345678"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(oclcNumber: "12345678"); // Act List result = _validator.TestValidate(bookCommand); @@ -1188,7 +1188,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidOclcNumber_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "invalid_oclc_number"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(oclcNumber: "invalid_oclc_number"); // Act List result = _validator.TestValidate(bookCommand); @@ -1201,7 +1201,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1214,7 +1214,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456M"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(openLibraryId: "OL123456M"); // Act List result = _validator.TestValidate(bookCommand); @@ -1227,7 +1227,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "InvalidID"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(openLibraryId: "InvalidID"); // Act List result = _validator.TestValidate(bookCommand); @@ -1240,7 +1240,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdStartsWithOLButIsInvalidFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123ABC"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(openLibraryId: "OL123ABC"); // Act List result = _validator.TestValidate(bookCommand); @@ -1253,7 +1253,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdHasValidFormatButInvalidSuffix_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456X"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(openLibraryId: "OL123456X"); // Act List result = _validator.TestValidate(bookCommand); @@ -1266,7 +1266,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1279,7 +1279,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidLibraryThingId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(50)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(libraryThingId: new Faker().Random.String2(50)); // Act List result = _validator.TestValidate(bookCommand); @@ -1292,7 +1292,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(51)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(libraryThingId: new Faker().Random.String2(51)); // Act List result = _validator.TestValidate(bookCommand); @@ -1305,7 +1305,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1318,7 +1318,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthGoogleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(googleBooksId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -1331,7 +1331,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidFormatGoogleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); + AddBookCommand bookCommand = _addBookCommandFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); // Act List result = _validator.TestValidate(bookCommand); @@ -1344,7 +1344,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); + AddBookCommand bookCommand = _addBookCommandFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); // Act List result = _validator.TestValidate(bookCommand); @@ -1357,7 +1357,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1370,7 +1370,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(11)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(barnesAndNobleId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -1383,7 +1383,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNonNumericBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.AlphaNumeric(10)); + AddBookCommand bookCommand = _addBookCommandFixture.Create(barnesAndNobleId: new Faker().Random.AlphaNumeric(10)); // Act List result = _validator.TestValidate(bookCommand); @@ -1396,7 +1396,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); + AddBookCommand bookCommand = _addBookCommandFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); // Act List result = _validator.TestValidate(bookCommand); @@ -1409,7 +1409,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyAppleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1422,7 +1422,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "id123456"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(appleBooksId: "id123456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1435,7 +1435,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "invalid_id"); + AddBookCommand bookCommand = _addBookCommandFixture.Create(appleBooksId: "invalid_id"); // Act List result = _validator.TestValidate(bookCommand); @@ -1448,7 +1448,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullIsbns_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1461,7 +1461,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyIsbnValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1474,7 +1474,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn10Value_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1487,7 +1487,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn13Value_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1500,7 +1500,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbnFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1513,7 +1513,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn10_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1526,7 +1526,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn13_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1539,7 +1539,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create() with { Contributors = null }; + AddBookCommand bookCommand = _addBookCommandFixture.Create() with { Contributors = null }; // Act List result = _validator.TestValidate(bookCommand); @@ -1552,7 +1552,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1565,7 +1565,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1578,7 +1578,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenContributorRoleIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1591,7 +1591,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + AddBookCommand bookCommand = _addBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1604,7 +1604,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeRatingValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1617,7 +1617,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 6, maxValue: 5)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 6, maxValue: 5)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1630,7 +1630,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeMaxRatingValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -1)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1643,7 +1643,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeVoteCount_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -1)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1656,7 +1656,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidRatings_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1669,7 +1669,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullVoteCount_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false)]); + AddBookCommand bookCommand = _addBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1682,7 +1682,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty.ToString()); + AddBookCommand bookCommand = _addBookCommandFixture.Create(libraryId: Guid.Empty.ToString()); // Act List result = _validator.TestValidate(bookCommand); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs index c7eb1b3e..865a1784 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandlerTests.cs @@ -52,7 +52,7 @@ public class UpdateBookCommandHandlerTests private readonly IValidator _mockValidator; private readonly UpdateBookCommandHandler _sut; private readonly Guid _userId; - private readonly UpdateBookCommandFixture _commandBookFixture = new(); + private readonly UpdateBookCommandFixture _updateBookCommandFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); @@ -61,6 +61,7 @@ public class UpdateBookCommandHandlerTests private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// @@ -97,14 +98,7 @@ public class UpdateBookCommandHandlerTests .Returns(callInfo => { IReadOnlyCollection contributorIds = callInfo.Arg>(); - return Result.From>([.. contributorIds.Select(contributorId => new MediaContributorEntity - { - Id = contributorId, - DisplayName = contributorId.ToString(), - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - })]); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); }); _sut = new UpdateBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); @@ -114,7 +108,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenCommandIsValid_ShouldUpdateBookAndReturnResponse() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); BookEntity? updatedBook = null; _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -142,7 +136,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutUpdating() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); _mockValidator.Validate(Arg.Any()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]); // Act @@ -159,7 +153,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); _mockCurrentUserService.UserId.Returns((Guid?)null); // Act @@ -175,7 +169,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(null)); @@ -193,7 +187,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Errors.Library.LibraryIdCannotBeEmpty); @@ -210,7 +204,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutUpdating() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); @@ -233,7 +227,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenRepositoryUpdateFails_ShouldReturnFailureResultWithoutSaving() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); @@ -254,7 +248,7 @@ public class UpdateBookCommandHandlerTests { // Arrange Guid contributorId = Guid.NewGuid(); - UpdateBookCommand command = _commandBookFixture.Create( + UpdateBookCommand command = _updateBookCommandFixture.Create( contributors: [ _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), @@ -291,7 +285,7 @@ public class UpdateBookCommandHandlerTests // Arrange Guid firstContributorId = Guid.NewGuid(); Guid secondContributorId = Guid.NewGuid(); - UpdateBookCommand command = _commandBookFixture.Create( + UpdateBookCommand command = _updateBookCommandFixture.Create( contributors: [ _mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author), @@ -324,7 +318,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidIsbn_ShouldReturnFailureResult() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + UpdateBookCommand command = _updateBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(existingBook)); @@ -343,7 +337,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); + UpdateBookCommand command = _updateBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(existingBook)); @@ -362,7 +356,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); + UpdateBookCommand command = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(existingBook)); @@ -381,7 +375,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")])); + UpdateBookCommand command = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")])); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(existingBook)); @@ -400,7 +394,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create( + UpdateBookCommand command = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create( originalReleaseDate: new DateOnly(2025, 1, 1), originalReleaseYear: 2025, reReleaseDate: new DateOnly(2024, 1, 1), @@ -423,7 +417,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + UpdateBookCommand command = _updateBookCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(existingBook)); @@ -444,7 +438,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); // The stored book belongs to a different library than the one named by the route. BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.NewGuid()); _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) @@ -465,7 +459,7 @@ public class UpdateBookCommandHandlerTests public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundErrorWithoutUpdating() { // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); + UpdateBookCommand command = _updateBookCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(existingBook)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs index 7f8efc2a..dd0a242a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidatorTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; @@ -26,7 +26,7 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.B [ExcludeFromCodeCoverage] public class UpdateBookCommandValidatorTests { - private readonly UpdateBookCommandFixture _commandBookFixture = new(); + private readonly UpdateBookCommandFixture _updateBookCommandFixture = new(); private readonly UpdateBookCommandValidator _validator = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); @@ -41,7 +41,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -54,7 +54,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(bookCommand); @@ -67,7 +67,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(bookCommand); @@ -80,7 +80,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); // Act List result = _validator.TestValidate(bookCommand); @@ -93,7 +93,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); // Act List result = _validator.TestValidate(bookCommand); @@ -106,7 +106,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -119,7 +119,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); // Act List result = _validator.TestValidate(bookCommand); @@ -132,7 +132,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); // Act List result = _validator.TestValidate(bookCommand); @@ -145,7 +145,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -158,7 +158,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenDescriptionIsEmpty_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: string.Empty)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: string.Empty)); // Act List result = _validator.TestValidate(bookCommand); @@ -171,7 +171,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -184,7 +184,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -197,7 +197,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); // Act List result = _validator.TestValidate(bookCommand); @@ -210,7 +210,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); // Act List result = _validator.TestValidate(bookCommand); @@ -223,7 +223,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -236,7 +236,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); // Act List result = _validator.TestValidate(bookCommand); @@ -249,7 +249,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); // Act List result = _validator.TestValidate(bookCommand); @@ -262,7 +262,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); // Act List result = _validator.TestValidate(bookCommand); @@ -275,7 +275,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -288,7 +288,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -301,7 +301,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -314,7 +314,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -327,7 +327,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -340,7 +340,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -353,7 +353,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(bookCommand); @@ -366,7 +366,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(bookCommand); @@ -379,7 +379,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(bookCommand); @@ -392,7 +392,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -405,7 +405,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); // Act List result = _validator.TestValidate(bookCommand); @@ -418,7 +418,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); // Act List result = _validator.TestValidate(bookCommand); @@ -431,7 +431,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); // Act List result = _validator.TestValidate(bookCommand); @@ -444,7 +444,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -457,7 +457,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -470,7 +470,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(bookCommand); @@ -483,7 +483,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -496,7 +496,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -509,7 +509,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -522,7 +522,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -535,7 +535,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -548,7 +548,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -561,7 +561,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -574,7 +574,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); // Act List result = _validator.TestValidate(bookCommand); @@ -587,7 +587,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); // Act List result = _validator.TestValidate(bookCommand); @@ -600,7 +600,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); // Act List result = _validator.TestValidate(bookCommand); @@ -613,7 +613,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -626,7 +626,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); // Act List result = _validator.TestValidate(bookCommand); @@ -639,7 +639,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); // Act List result = _validator.TestValidate(bookCommand); @@ -652,7 +652,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithEmptyPublisher_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -665,7 +665,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidPublisher_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); // Act List result = _validator.TestValidate(bookCommand); @@ -678,7 +678,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthPublisher_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(101))); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(101))); // Act List result = _validator.TestValidate(bookCommand); @@ -691,7 +691,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenPageCountIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); // Act List result = _validator.TestValidate(bookCommand); @@ -704,7 +704,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenPageCountIsZero_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 0)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 0)); // Act List result = _validator.TestValidate(bookCommand); @@ -717,7 +717,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenPageCountIsNegative_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); // Act List result = _validator.TestValidate(bookCommand); @@ -730,7 +730,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenPageCountIsPositive_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); // Act List result = _validator.TestValidate(bookCommand); @@ -743,7 +743,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenFormatIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -756,7 +756,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenFormatIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(format: BookFormat.Hardcover); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(format: BookFormat.Hardcover); // Act List result = _validator.TestValidate(bookCommand); @@ -769,7 +769,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(format: (BookFormat)99); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(format: (BookFormat)99); // Act List result = _validator.TestValidate(bookCommand); @@ -782,7 +782,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenEditionIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -795,7 +795,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenEditionIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(50)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(edition: new Faker().Random.String2(50)); // Act List result = _validator.TestValidate(bookCommand); @@ -808,7 +808,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(51)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(edition: new Faker().Random.String2(51)); // Act List result = _validator.TestValidate(bookCommand); @@ -821,7 +821,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -834,7 +834,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenVolumeNumberIsZero_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 0); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(volumeNumber: 0); // Act List result = _validator.TestValidate(bookCommand); @@ -847,7 +847,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: -1); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(volumeNumber: -1); // Act List result = _validator.TestValidate(bookCommand); @@ -860,7 +860,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenVolumeNumberIsPositive_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 1); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(volumeNumber: 1); // Act List result = _validator.TestValidate(bookCommand); @@ -873,7 +873,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenSeriesIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(); // Act List result = _validator.TestValidate(bookCommand); @@ -886,7 +886,7 @@ public class UpdateBookCommandValidatorTests //public void Validate_WhenSeriesTitleIsEmpty_ShouldHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.Create(); + // var bookCommand = _updateBookCommandFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = string.Empty } }; // // Act @@ -900,7 +900,7 @@ public class UpdateBookCommandValidatorTests //public void Validate_WhenSeriesTitleExceeds255Characters_ShouldHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.Create(); + // var bookCommand = _updateBookCommandFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(256) } }; // // Act @@ -914,7 +914,7 @@ public class UpdateBookCommandValidatorTests //public void Validate_WhenSeriesTitleIsValid_ShouldNotHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.Create(); + // var bookCommand = _updateBookCommandFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(200) } }; // // Act @@ -928,7 +928,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenAsinIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(10)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(asin: new Faker().Random.String2(10)); // Act List result = _validator.TestValidate(bookCommand); @@ -941,7 +941,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenAsinIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -954,7 +954,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(9)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(asin: new Faker().Random.String2(9)); // Act List result = _validator.TestValidate(bookCommand); @@ -967,7 +967,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -980,7 +980,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123456789"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(goodreadsId: "123456789"); // Act List result = _validator.TestValidate(bookCommand); @@ -993,7 +993,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "abc123"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(goodreadsId: "abc123"); // Act List result = _validator.TestValidate(bookCommand); @@ -1006,7 +1006,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpaces_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123 456"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(goodreadsId: "123 456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1019,7 +1019,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpecialCharacters_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123-456"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(goodreadsId: "123-456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1032,7 +1032,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLccnIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1045,7 +1045,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLccnIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "n78890351"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(lccn: "n78890351"); // Act List result = _validator.TestValidate(bookCommand); @@ -1058,7 +1058,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "invalid123"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(lccn: "invalid123"); // Act List result = _validator.TestValidate(bookCommand); @@ -1071,7 +1071,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLccnIsTooLong_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: new Faker().Random.String2(15)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(lccn: new Faker().Random.String2(15)); // Act List result = _validator.TestValidate(bookCommand); @@ -1084,7 +1084,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLccnIsTooShort_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "n12"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(lccn: "n12"); // Act List result = _validator.TestValidate(bookCommand); @@ -1097,7 +1097,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithEmptyOclcNumber_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1110,7 +1110,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat1_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocm12345678"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(oclcNumber: "ocm12345678"); // Act List result = _validator.TestValidate(bookCommand); @@ -1123,7 +1123,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat2_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocn123456789"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(oclcNumber: "ocn123456789"); // Act List result = _validator.TestValidate(bookCommand); @@ -1136,7 +1136,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat3_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "on1234567890"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(oclcNumber: "on1234567890"); // Act List result = _validator.TestValidate(bookCommand); @@ -1149,7 +1149,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat4_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "(OCoLC)1234567890"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(oclcNumber: "(OCoLC)1234567890"); // Act List result = _validator.TestValidate(bookCommand); @@ -1162,7 +1162,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat5_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "12345678"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(oclcNumber: "12345678"); // Act List result = _validator.TestValidate(bookCommand); @@ -1175,7 +1175,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidOclcNumber_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "invalid_oclc_number"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(oclcNumber: "invalid_oclc_number"); // Act List result = _validator.TestValidate(bookCommand); @@ -1188,7 +1188,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1201,7 +1201,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456M"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(openLibraryId: "OL123456M"); // Act List result = _validator.TestValidate(bookCommand); @@ -1214,7 +1214,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsInvalid_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "InvalidID"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(openLibraryId: "InvalidID"); // Act List result = _validator.TestValidate(bookCommand); @@ -1227,7 +1227,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOpenLibraryIdStartsWithOLButIsInvalidFormat_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123ABC"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(openLibraryId: "OL123ABC"); // Act List result = _validator.TestValidate(bookCommand); @@ -1240,7 +1240,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenOpenLibraryIdHasValidFormatButInvalidSuffix_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456X"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(openLibraryId: "OL123456X"); // Act List result = _validator.TestValidate(bookCommand); @@ -1253,7 +1253,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1266,7 +1266,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidLibraryThingId_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(50)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(libraryThingId: new Faker().Random.String2(50)); // Act List result = _validator.TestValidate(bookCommand); @@ -1279,7 +1279,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(51)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(libraryThingId: new Faker().Random.String2(51)); // Act List result = _validator.TestValidate(bookCommand); @@ -1292,7 +1292,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithEmptyGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1305,7 +1305,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthGoogleBooksId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(googleBooksId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -1318,7 +1318,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidFormatGoogleBooksId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); // Act List result = _validator.TestValidate(bookCommand); @@ -1331,7 +1331,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); // Act List result = _validator.TestValidate(bookCommand); @@ -1344,7 +1344,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithEmptyBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1357,7 +1357,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(11)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(barnesAndNobleId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -1370,7 +1370,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithNonNumericBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.AlphaNumeric(10)); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(barnesAndNobleId: new Faker().Random.AlphaNumeric(10)); // Act List result = _validator.TestValidate(bookCommand); @@ -1383,7 +1383,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); // Act List result = _validator.TestValidate(bookCommand); @@ -1396,7 +1396,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithEmptyAppleBooksId_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1409,7 +1409,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "id123456"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(appleBooksId: "id123456"); // Act List result = _validator.TestValidate(bookCommand); @@ -1422,7 +1422,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "invalid_id"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(appleBooksId: "invalid_id"); // Act List result = _validator.TestValidate(bookCommand); @@ -1435,7 +1435,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithNullIsbns_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1448,7 +1448,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithEmptyIsbnValue_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1461,7 +1461,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn10Value_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1474,7 +1474,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn13Value_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1487,7 +1487,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbnFormat_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1500,7 +1500,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn10_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1513,7 +1513,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn13_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1526,7 +1526,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create() with { Contributors = null }; + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create() with { Contributors = null }; // Act List result = _validator.TestValidate(bookCommand); @@ -1539,7 +1539,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1552,7 +1552,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1565,7 +1565,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenContributorRoleIsInvalid_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1578,7 +1578,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(includeFormat: false, includeEdition: false, includeVolumeNumber: false, includeAsin: false, includeGoodreadsId: false, includeLccn: false, includeOclcNumber: false, includeOpenLibraryId: false, includeLibraryThingId: false, includeGoogleBooksId: false, includeBarnesAndNobleId: false, includeAppleBooksId: false, includeIsbns: false, includeRatings: false, includeContributors: false); // Act List result = _validator.TestValidate(bookCommand); @@ -1591,7 +1591,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithNegativeRatingValue_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1604,7 +1604,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 6, maxValue: 5)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 6, maxValue: 5)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1617,7 +1617,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithNegativeMaxRatingValue_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -1)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1630,7 +1630,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithNegativeVoteCount_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -1)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -1)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1643,7 +1643,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithValidRatings_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1656,7 +1656,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenCalledWithNullVoteCount_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false)]); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1669,7 +1669,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty.ToString()); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(libraryId: Guid.Empty.ToString()); // Act List result = _validator.TestValidate(bookCommand); @@ -1682,7 +1682,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: "not-a-guid"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(libraryId: "not-a-guid"); // Act List result = _validator.TestValidate(bookCommand); @@ -1695,7 +1695,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.NewGuid().ToString()); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); // Act List result = _validator.TestValidate(bookCommand); @@ -1708,7 +1708,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: Guid.Empty.ToString()); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(bookId: Guid.Empty.ToString()); // Act List result = _validator.TestValidate(bookCommand); @@ -1721,7 +1721,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenBookIdIsNotAGuid_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: "not-a-guid"); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(bookId: "not-a-guid"); // Act List result = _validator.TestValidate(bookCommand); @@ -1734,7 +1734,7 @@ public class UpdateBookCommandValidatorTests public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: Guid.NewGuid().ToString()); + UpdateBookCommand bookCommand = _updateBookCommandFixture.Create(bookId: Guid.NewGuid().ToString()); // Act List result = _validator.TestValidate(bookCommand); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandlerTests.cs index 5794b4e8..0aa957de 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandlerTests.cs @@ -49,7 +49,7 @@ public class UpdateBookCoverCommandHandlerTests private readonly IValidator _mockValidator; private readonly UpdateBookCoverCommandHandler _sut; private readonly Guid _userId; - private readonly UpdateBookCoverCommandFixture _commandFixture = new(); + private readonly UpdateBookCoverCommandFixture _updateBookCoverCommandFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); @@ -91,7 +91,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenBookHasNoExistingCover_ShouldStoreArtworkAndAddCoverArtwork() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); existingBook.Artwork = []; LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); @@ -126,7 +126,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenBookHasExistingCover_ShouldReplaceTheStoredCoverFile() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: Guid.Parse(command.BookId!), artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg"); existingBook.Artwork = [existingCover]; @@ -153,7 +153,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenBookHasAuthorContributors_ShouldPassTheResolvedAuthorNameToArtworkService() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "J.R.R. Tolkien"); MediaContributorEntity illustrator = _mediaContributorEntityFixture.Create(displayName: "Alan Lee"); @@ -190,7 +190,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenAuthorResolutionFails_ShouldReturnFailureResultWithoutStoringArtwork() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); existingBook.Contributors = [ @@ -218,7 +218,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutStoringArtwork() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); _mockValidator.Validate(Arg.Any()).Returns([Errors.WrittenContent.BookCoverCannotBeNull]); // Act @@ -235,7 +235,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); _mockCurrentUserService.UserId.Returns((Guid?)null); // Act @@ -251,7 +251,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(null)); @@ -269,7 +269,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutStoringArtwork() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); @@ -290,7 +290,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); @@ -311,7 +311,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenArtworkStorageFails_ShouldReturnFailureResultWithoutSaving() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) @@ -334,7 +334,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); // The stored book belongs to a different library than the one named by the route. BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.NewGuid()); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) @@ -355,7 +355,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenBookRepositoryReturnsError_ShouldReturnFailureResult() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Errors.Library.LibraryIdCannotBeEmpty); @@ -374,7 +374,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); @@ -395,7 +395,7 @@ public class UpdateBookCoverCommandHandlerTests public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReturningTheCoverPath() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidatorTests.cs index 8e3cfcfb..f6f1a0da 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidatorTests.cs @@ -17,14 +17,14 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.B [ExcludeFromCodeCoverage] public class UpdateBookCoverCommandValidatorTests { - private readonly UpdateBookCoverCommandFixture _commandFixture = new(); + private readonly UpdateBookCoverCommandFixture _updateBookCoverCommandFixture = new(); private readonly UpdateBookCoverCommandValidator _validator = new(); [Fact] public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(); // Act List result = _validator.TestValidate(command); @@ -37,7 +37,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(libraryId: Guid.Empty.ToString()); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(libraryId: Guid.Empty.ToString()); // Act List result = _validator.TestValidate(command); @@ -50,7 +50,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(libraryId: "not-a-guid"); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(libraryId: "not-a-guid"); // Act List result = _validator.TestValidate(command); @@ -63,7 +63,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(libraryId: Guid.NewGuid().ToString()); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); // Act List result = _validator.TestValidate(command); @@ -76,7 +76,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty.ToString()); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: Guid.Empty.ToString()); // Act List result = _validator.TestValidate(command); @@ -89,7 +89,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenBookIdIsNotAGuid_ShouldHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(bookId: "not-a-guid"); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: "not-a-guid"); // Act List result = _validator.TestValidate(command); @@ -102,7 +102,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.NewGuid().ToString()); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(bookId: Guid.NewGuid().ToString()); // Act List result = _validator.TestValidate(command); @@ -115,7 +115,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenCoverIsNull_ShouldHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(includeCover: false); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(includeCover: false); // Act List result = _validator.TestValidate(command); @@ -128,7 +128,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenCoverIsPresentAndFileNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(fileName: string.Empty); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(fileName: string.Empty); // Act List result = _validator.TestValidate(command); @@ -141,7 +141,7 @@ public class UpdateBookCoverCommandValidatorTests public void Validate_WhenCoverIsMissingAndFileNameIsEmpty_ShouldNotHaveFileNameValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(fileName: string.Empty, includeCover: false); + UpdateBookCoverCommand command = _updateBookCoverCommandFixture.Create(fileName: string.Empty, includeCover: false); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidatorTests.cs index dca3023a..d757aa21 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidatorTests.cs @@ -16,14 +16,14 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.B [ExcludeFromCodeCoverage] public class GetBookQueryValidatorTests { - private readonly GetBookQueryFixture _queryBookFixture = new(); + private readonly GetBookQueryFixture _getBookQueryFixture = new(); private readonly GetBookQueryValidator _validator = new(); [Fact] public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError() { // Arrange - GetBookQuery query = _queryBookFixture.Create(); + GetBookQuery query = _getBookQueryFixture.Create(); // Act List result = _validator.TestValidate(query); @@ -41,7 +41,7 @@ public class GetBookQueryValidatorTests public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) { // Arrange - GetBookQuery query = _queryBookFixture.Create() with { LibraryId = libraryId }; + GetBookQuery query = _getBookQueryFixture.Create() with { LibraryId = libraryId }; // Act List result = _validator.TestValidate(query); @@ -58,7 +58,7 @@ public class GetBookQueryValidatorTests public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId) { // Arrange - GetBookQuery query = _queryBookFixture.Create() with { BookId = bookId }; + GetBookQuery query = _getBookQueryFixture.Create() with { BookId = bookId }; // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs index 032fc332..30b0c080 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs @@ -34,7 +34,7 @@ public class ReorderLibraryArtworkProvidersCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; private readonly ReorderLibraryArtworkProvidersCommandHandler _sut; - private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); private readonly Guid _userId; @@ -66,8 +66,8 @@ public class ReorderLibraryArtworkProvidersCommandHandlerTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); - LibraryArtworkProviderConfigurationEntity secondProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity firstProvider = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); + LibraryArtworkProviderConfigurationEntity secondProvider = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(new List { firstProvider, secondProvider }); _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) @@ -92,7 +92,7 @@ public class ReorderLibraryArtworkProvidersCommandHandlerTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity configuration = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); Guid unknownPluginId = Guid.NewGuid(); _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(new List { configuration }); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs index c21aa390..a69c80e9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -34,7 +34,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; private readonly ReorderLibraryMetadataProvidersCommandHandler _sut; - private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new(); private readonly Guid _userId; @@ -66,8 +66,8 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); - LibraryMetadataProviderConfigurationEntity secondProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity firstProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); + LibraryMetadataProviderConfigurationEntity secondProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(new List { firstProvider, secondProvider }); _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs index 7b838254..45b02578 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs @@ -36,7 +36,7 @@ public class SetLibraryBookReaderEnabledCommandHandlerTests private readonly IValidator _mockValidator; private readonly SetLibraryBookReaderEnabledCommandHandler _sut; private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new(); - private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); private readonly Guid _userId; /// @@ -93,7 +93,7 @@ public class SetLibraryBookReaderEnabledCommandHandlerTests { // Arrange SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: true); - LibraryBookReaderConfigurationEntity existingConfiguration = _configurationEntityFixture.Create( + LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create( libraryId: command.LibraryId, pluginId: command.PluginId, isEnabled: false); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs index 6b90b6d9..01fc4170 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs @@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Errors; @@ -39,8 +40,9 @@ public class GetLibraryArtworkProvidersQueryHandlerTests private readonly IValidator _mockValidator; private readonly GetLibraryArtworkProvidersQueryHandler _sut; private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly Guid _userId; /// @@ -93,8 +95,8 @@ public class GetLibraryArtworkProvidersQueryHandlerTests Guid secondPluginId = Guid.NewGuid(); List configurations = [ - _configurationEntityFixture.Create(query.LibraryId, secondPluginId, 2), - _configurationEntityFixture.Create(query.LibraryId, firstPluginId, 1) + _libraryArtworkProviderConfigurationEntityFixture.Create(query.LibraryId, secondPluginId, 2), + _libraryArtworkProviderConfigurationEntityFixture.Create(query.LibraryId, firstPluginId, 1) ]; _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); @@ -104,7 +106,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests _pluginEntityFixture.Create(secondPluginId) ]; _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -127,12 +129,12 @@ public class GetLibraryArtworkProvidersQueryHandlerTests Guid unknownPluginId = Guid.NewGuid(); List configurations = [ - _configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1) + _libraryArtworkProviderConfigurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1) ]; _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [_pluginEntityFixture.Create()], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -152,7 +154,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandlerTests.cs index 3a20d7dd..f3b1c03e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandlerTests.cs @@ -11,6 +11,7 @@ using Lumina.Application.Common.Infrastructure.Reading; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryBookReaders; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Errors; @@ -41,8 +42,9 @@ public class GetLibraryBookReadersQueryHandlerTests private readonly IValidator _mockValidator; private readonly GetLibraryBookReadersQueryHandler _sut; private readonly GetLibraryBookReadersQueryFixture _getLibraryBookReadersQueryFixture = new(); - private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly Guid _userId; /// @@ -97,8 +99,8 @@ public class GetLibraryBookReadersQueryHandlerTests Guid disabledPluginId = Guid.NewGuid(); List configurations = [ - _configurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: enabledPluginId, isEnabled: true), - _configurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: disabledPluginId, isEnabled: false) + _libraryBookReaderConfigurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: enabledPluginId, isEnabled: true), + _libraryBookReaderConfigurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: disabledPluginId, isEnabled: false) ]; _mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); @@ -108,7 +110,7 @@ public class GetLibraryBookReadersQueryHandlerTests _pluginEntityFixture.Create(disabledPluginId, "B Reader") ]; _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); Dictionary> supportedExtensions = new() { [enabledPluginId] = [".epub"], @@ -138,12 +140,12 @@ public class GetLibraryBookReadersQueryHandlerTests Guid unknownPluginId = Guid.NewGuid(); List configurations = [ - _configurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: unknownPluginId, isEnabled: true) + _libraryBookReaderConfigurationEntityFixture.Create(libraryId: query.LibraryId, pluginId: unknownPluginId, isEnabled: true) ]; _mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [_pluginEntityFixture.Create()], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -164,7 +166,7 @@ public class GetLibraryBookReadersQueryHandlerTests _mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs index 6c456d79..3bd9b074 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs @@ -11,6 +11,7 @@ using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Errors; @@ -40,8 +41,9 @@ public class GetLibraryMetadataProvidersQueryHandlerTests private readonly IValidator _mockValidator; private readonly GetLibraryMetadataProvidersQueryHandler _sut; private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly Guid _userId; /// @@ -93,8 +95,8 @@ public class GetLibraryMetadataProvidersQueryHandlerTests Guid secondPluginId = Guid.NewGuid(); List configurations = [ - _configurationEntityFixture.Create(query.LibraryId, secondPluginId, 2), - _configurationEntityFixture.Create(query.LibraryId, firstPluginId, 1) + _libraryMetadataProviderConfigurationEntityFixture.Create(query.LibraryId, secondPluginId, 2), + _libraryMetadataProviderConfigurationEntityFixture.Create(query.LibraryId, firstPluginId, 1) ]; _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); @@ -104,7 +106,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests _pluginEntityFixture.Create(secondPluginId) ]; _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -127,12 +129,12 @@ public class GetLibraryMetadataProvidersQueryHandlerTests Guid unknownPluginId = Guid.NewGuid(); List configurations = [ - _configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1) + _libraryMetadataProviderConfigurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1) ]; _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [_pluginEntityFixture.Create()], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -152,7 +154,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs index e1387496..bf570159 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Plugins.Queries.GetPlugins; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPlugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Primitives; @@ -29,6 +30,7 @@ public class GetPluginsQueryHandlerTests private readonly GetPluginsQueryHandler _sut; private readonly GetPluginsQueryFixture _getPluginsQueryFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -48,7 +50,7 @@ public class GetPluginsQueryHandlerTests // Arrange List plugins = [_pluginEntityFixture.Create(), _pluginEntityFixture.Create()]; _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs index bcb83c98..c2e2b278 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.Responses.Scheduling; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; @@ -35,6 +36,7 @@ public class ScheduledJobAddedDomainEventHandlerTests private readonly ScheduledJobAddedDomainEventHandler _sut; private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly ScheduledJobAddedDomainEventFixture _scheduledJobAddedDomainEventFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -47,7 +49,7 @@ public class ScheduledJobAddedDomainEventHandlerTests _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _sut = new ScheduledJobAddedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -59,7 +61,7 @@ public class ScheduledJobAddedDomainEventHandlerTests ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(); ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1"); ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2"); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [scheduledJob1, scheduledJob2], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [scheduledJob1, scheduledJob2], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs index 247f2aaa..bb2a6225 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Scheduling; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.Responses.Scheduling; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; @@ -34,6 +35,7 @@ public class ScheduledJobCycleStartedDomainEventHandlerTests private readonly IScheduledJobRepository _mockScheduledJobRepository; private readonly ScheduledJobCycleStartedDomainEventHandler _sut; private readonly ScheduledJobCycleStartedDomainEventFixture _scheduledJobCycleStartedDomainEventFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -47,7 +49,7 @@ public class ScheduledJobCycleStartedDomainEventHandlerTests _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _sut = new ScheduledJobCycleStartedDomainEventHandler(_mockScheduledJobNotifier, _mockScheduledJobScheduler, _mockUnitOfWork); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs index 79a52e25..cf216ace 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.Responses.Scheduling; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; @@ -34,6 +35,7 @@ public class ScheduledJobCycleStoppedDomainEventHandlerTests private readonly ScheduledJobCycleStoppedDomainEventHandler _sut; private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly ScheduledJobCycleStoppedDomainEventFixture _scheduledJobCycleStoppedDomainEventFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -46,7 +48,7 @@ public class ScheduledJobCycleStoppedDomainEventHandlerTests _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _sut = new ScheduledJobCycleStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -57,7 +59,7 @@ public class ScheduledJobCycleStoppedDomainEventHandlerTests // Arrange ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create(); ScheduledJobEntity stoppedJob = _scheduledJobEntityFixture.Create(name: "Stopped job", status: Lumina.Domain.SharedKernel.Common.Enums.Scheduling.ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [stoppedJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [stoppedJob], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs index 58f87229..f09c034a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.Responses.Scheduling; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Exceptions; @@ -38,6 +39,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); private readonly ScheduledJobExecutionCompletedDomainEventFixture _scheduledJobExecutionCompletedDomainEventFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -54,7 +56,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _sut = new ScheduledJobExecutionCompletedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs index 7c453083..cdc0fd9a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.Responses.Scheduling; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Exceptions; @@ -39,6 +40,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); private readonly ScheduledJobExecutionStartedDomainEventFixture _scheduledJobExecutionStartedDomainEventFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -55,7 +57,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockScheduledJobExecutionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _sut = new ScheduledJobExecutionStartedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs index 9daedcc6..bbdd38b1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.Responses.Scheduling; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; @@ -35,6 +36,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandlerTests private readonly ScheduledJobExecutionStoppedDomainEventHandler _sut; private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); private readonly ScheduledJobExecutionStoppedDomainEventFixture _scheduledJobExecutionStoppedDomainEventFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -50,7 +52,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandlerTests _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _sut = new ScheduledJobExecutionStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs index 689fdd5d..bcdaf901 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.Responses.Scheduling; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; @@ -34,6 +35,7 @@ public class ScheduledJobRemovedDomainEventHandlerTests private readonly ScheduledJobRemovedDomainEventHandler _sut; private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly ScheduledJobRemovedDomainEventFixture _scheduledJobRemovedDomainEventFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -46,7 +48,7 @@ public class ScheduledJobRemovedDomainEventHandlerTests _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _sut = new ScheduledJobRemovedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -57,7 +59,7 @@ public class ScheduledJobRemovedDomainEventHandlerTests // Arrange ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(); ScheduledJobEntity remainingJob = _scheduledJobEntityFixture.Create(name: "Remaining job"); - _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [remainingJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [remainingJob], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs index a3f47aaf..eb23b91a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Contracts.Responses.Scheduling; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -34,6 +35,7 @@ public class GetScheduledJobsQueryHandlerTests private readonly IScheduledJobRepository _mockScheduledJobRepository; private readonly GetScheduledJobsQueryHandler _sut; private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly Guid _userId = Guid.NewGuid(); /// @@ -61,7 +63,7 @@ public class GetScheduledJobsQueryHandlerTests ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1"); ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2"); _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [scheduledJob1, scheduledJob2], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [scheduledJob1, scheduledJob2], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); @@ -78,7 +80,7 @@ public class GetScheduledJobsQueryHandlerTests { // Arrange _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs index acbe0343..55f336ce 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs @@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Themes.Management.Commands.DeleteTheme; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -41,6 +42,7 @@ public class DeleteThemeCommandHandlerTests private readonly DeleteThemeCommandHandler _sut; private readonly DeleteThemeCommandFixture _deleteThemeCommandFixture = new(); private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly Guid _userId; /// @@ -210,7 +212,7 @@ public class DeleteThemeCommandHandlerTests _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [theme, userTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [theme, userTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -232,7 +234,7 @@ public class DeleteThemeCommandHandlerTests _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [theme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [theme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -255,7 +257,7 @@ public class DeleteThemeCommandHandlerTests _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [theme, otherBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [theme, otherBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -282,7 +284,7 @@ public class DeleteThemeCommandHandlerTests _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [theme, bundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [theme, bundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) .Returns(Result.Deleted); @@ -308,7 +310,7 @@ public class DeleteThemeCommandHandlerTests _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [theme, bundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [theme, bundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) .Returns(error); @@ -333,7 +335,7 @@ public class DeleteThemeCommandHandlerTests _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [theme, replacementTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [theme, replacementTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -364,7 +366,7 @@ public class DeleteThemeCommandHandlerTests _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [theme, betaTheme, alphaTheme], CurrentPage = 1, PerPage = 3, Count = 3, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [theme, betaTheme, alphaTheme], currentPage: 1, perPage: 3, count: 3, numberOfPages: 1))); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -392,7 +394,7 @@ public class DeleteThemeCommandHandlerTests _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [theme, bundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [theme, bundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) .Returns(Result.Deleted); _mockThemeService.DeleteAsync(theme.ThemeId, Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs index bf076d7e..ef4ce400 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Themes.Management.Queries.GetThemes; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemes; using Lumina.Contracts.Responses.Themes; using Lumina.Domain.Common.Primitives; @@ -30,6 +31,7 @@ public class GetThemesQueryHandlerTests private readonly GetThemesQueryHandler _sut; private readonly GetThemesQueryFixture _getThemesQueryFixture = new(); private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -53,7 +55,7 @@ public class GetThemesQueryHandlerTests ThemeEntity bundledUpperTheme = _themeEntityFixture.Create(themeId: "bundled-upper", name: "Banana", installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "deleted-theme", name: "Deleted", installSource: ThemeInstallSource.Uploaded, isDeleted: true); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [uploadedTheme, bundledLowerTheme, bundledUpperTheme, deletedTheme], CurrentPage = 1, PerPage = 4, Count = 4, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [uploadedTheme, bundledLowerTheme, bundledUpperTheme, deletedTheme], currentPage: 1, perPage: 4, count: 4, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -77,7 +79,7 @@ public class GetThemesQueryHandlerTests // Arrange GetThemesQuery query = _getThemesQueryFixture.Create(); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs index 9cf3f7ee..d8c18fa5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -29,6 +30,7 @@ public class ChangePasswordCommandHandlerTests private readonly IUserRepository _mockUserRepository; private readonly ChangePasswordCommandHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly ChangePasswordCommandFixture _changePasswordCommandFixture = new(); /// /// Initializes a new instance of the class. @@ -63,7 +65,7 @@ public class ChangePasswordCommandHandlerTests UserEntity user = _userEntityFixture.Create(); user.Password = escapedHashedCurrentPassword; - ChangePasswordCommand command = new( + ChangePasswordCommand command = _changePasswordCommandFixture.Create( user.Username, currentPassword, newPassword, @@ -96,7 +98,7 @@ public class ChangePasswordCommandHandlerTests public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError() { // Arrange - ChangePasswordCommand command = new("nonexistentUser", "oldPass", "newPass", "newPass"); + ChangePasswordCommand command = _changePasswordCommandFixture.Create("nonexistentUser", "oldPass", "newPass", "newPass"); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) .Returns(Result.From(null)); @@ -120,7 +122,7 @@ public class ChangePasswordCommandHandlerTests UserEntity user = _userEntityFixture.Create(); string incorrectPassword = "wrongPassword"; - ChangePasswordCommand command = new( + ChangePasswordCommand command = _changePasswordCommandFixture.Create( user.Username, incorrectPassword, "newPass", @@ -156,7 +158,7 @@ public class ChangePasswordCommandHandlerTests UserEntity user = _userEntityFixture.Create(); user.Password = escapedHashedCurrentPassword; - ChangePasswordCommand command = new( + ChangePasswordCommand command = _changePasswordCommandFixture.Create( user.Username, currentPassword, newPassword, @@ -189,7 +191,7 @@ public class ChangePasswordCommandHandlerTests string currentPassword = "currentPassword"; string newPassword = "newPassword"; UserEntity user = _userEntityFixture.Create(); - ChangePasswordCommand command = new( + ChangePasswordCommand command = _changePasswordCommandFixture.Create( user.Username, currentPassword, newPassword, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs index 91a0a558..ad98c6f2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -32,6 +33,7 @@ public class RecoverPasswordCommandHandlerTests private readonly IUserRepository _mockUserRepository; private readonly RecoverPasswordCommandHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly RecoverPasswordCommandFixture _recoverPasswordCommandFixture = new(); /// /// Initializes a new instance of the class. @@ -71,7 +73,7 @@ public class RecoverPasswordCommandHandlerTests user.TotpSecret = encryptedTotpSecret; user.TempPassword = null; - RecoverPasswordCommand command = new(user.Username, totpCode); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -102,7 +104,7 @@ public class RecoverPasswordCommandHandlerTests public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError() { // Arrange - RecoverPasswordCommand command = new("nonexistentUser", "123456"); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create("nonexistentUser", "123456"); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) .Returns(Result.From(null)); @@ -127,7 +129,7 @@ public class RecoverPasswordCommandHandlerTests user.TempPassword = "existingTempPassword"; user.TempPasswordCreated = DateTime.UtcNow; - RecoverPasswordCommand command = new(user.Username, "123456"); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, "123456"); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -151,7 +153,7 @@ public class RecoverPasswordCommandHandlerTests UserEntity user = _userEntityFixture.Create(); user.TotpSecret = null; - RecoverPasswordCommand command = new(user.Username, "123456"); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, "123456"); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -179,7 +181,7 @@ public class RecoverPasswordCommandHandlerTests UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; - RecoverPasswordCommand command = new(user.Username, totpCode); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -213,7 +215,7 @@ public class RecoverPasswordCommandHandlerTests UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; - RecoverPasswordCommand command = new(user.Username, totpCode); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -247,7 +249,7 @@ public class RecoverPasswordCommandHandlerTests UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; - RecoverPasswordCommand command = new(user.Username, totpCode); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, totpCode); Error error = Error.Failure("Database.Error", "Failed to check username"); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) @@ -274,7 +276,7 @@ public class RecoverPasswordCommandHandlerTests UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; - RecoverPasswordCommand command = new(user.Username, null); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(user.Username, includeTotpCode: false); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs index 85c6267e..6fbcd427 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs @@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.GetUsers; using Lumina.Contracts.Responses.UsersManagement.Users; using Lumina.Domain.Common.Primitives; @@ -35,6 +36,7 @@ public class GetUsersQueryHandlerTests private readonly IUserRepository _mockUserRepository; private readonly GetUsersQueryHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly GetUsersQueryFixture _getUsersQueryFixture = new(); private readonly Guid _userId; @@ -124,7 +126,7 @@ public class GetUsersQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = users, CurrentPage = 1, PerPage = users.Count, Count = users.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: users, currentPage: 1, perPage: users.Count, count: users.Count, numberOfPages: 1))); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs index 2d2d6761..963570f9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -35,6 +36,7 @@ public class LoginUserQueryHandlerTests private readonly IDateTimeProvider _mockDateTimeProvider; private readonly LoginUserQueryHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginUserQueryFixture _loginUserQueryFixture = new(); /// /// Initializes a new instance of the class. @@ -78,7 +80,7 @@ public class LoginUserQueryHandlerTests user.Password = Uri.EscapeDataString(hashedPassword); user.TotpSecret = null; - LoginUserQuery query = new(user.Username, password); + LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -113,7 +115,7 @@ public class LoginUserQueryHandlerTests user.Password = Uri.EscapeDataString(hashedPassword); user.TotpSecret = encryptedTotpSecret; - LoginUserQuery query = new(user.Username, password, totpCode); + LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password, totpCode: totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -141,7 +143,7 @@ public class LoginUserQueryHandlerTests public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnError() { // Arrange - LoginUserQuery query = new("nonexistentUser", "password"); + LoginUserQuery query = _loginUserQueryFixture.Create("nonexistentUser", "password"); _mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any()) .Returns(Result.From(null)); @@ -165,7 +167,7 @@ public class LoginUserQueryHandlerTests user.Password = Uri.EscapeDataString(hashedPassword); user.TempPassword = null; - LoginUserQuery query = new(user.Username, password); + LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -193,7 +195,7 @@ public class LoginUserQueryHandlerTests user.TempPassword = Uri.EscapeDataString(hashedTempPassword); user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (more than 15 minutes old) - LoginUserQuery query = new(user.Username, password); + LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -231,7 +233,7 @@ public class LoginUserQueryHandlerTests user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); user.TotpSecret = null; // Ensure no TOTP validation is needed - LoginUserQuery query = new(user.Username, password); + LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -265,7 +267,7 @@ public class LoginUserQueryHandlerTests user.Password = Uri.EscapeDataString(hashedPassword); user.TotpSecret = encryptedTotpSecret; - LoginUserQuery query = new(user.Username, password); + LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -294,7 +296,7 @@ public class LoginUserQueryHandlerTests user.Password = Uri.EscapeDataString(hashedPassword); user.TotpSecret = encryptedTotpSecret; - LoginUserQuery query = new(user.Username, password, totpCode); + LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password, totpCode: totpCode); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); @@ -317,7 +319,7 @@ public class LoginUserQueryHandlerTests public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError() { // Arrange - LoginUserQuery query = new("username", "password"); + LoginUserQuery query = _loginUserQueryFixture.Create("username", "password"); Error error = Error.Failure("Database.Error", "Failed to retrieve user"); _mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any()) @@ -344,7 +346,7 @@ public class LoginUserQueryHandlerTests user.TempPassword = Uri.EscapeDataString(hashedTempPassword); user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); // Valid timeframe - LoginUserQuery query = new(user.Username, password); + LoginUserQuery query = _loginUserQueryFixture.Create(user.Username, password); _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) .Returns(Result.From(user)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs index 11888a15..4f70fed7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs @@ -12,6 +12,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -49,6 +50,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); private readonly UpdateUserRoleAndPermissionsCommandFixture _updateUserRoleAndPermissionsCommandFixture = new(); private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly Guid _userId; /// @@ -180,7 +182,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(newRole); _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = users, CurrentPage = 1, PerPage = users.Count, Count = users.Count, NumberOfPages = 1 })); + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: users, currentPage: 1, perPage: users.Count, count: users.Count, numberOfPages: 1))); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs index c8c98f9d..8f8a391f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; +using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Primitives; using System; @@ -18,12 +19,13 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Comman public class UpdateUserRoleAndPermissionsCommandValidatorTests { private readonly UpdateUserRoleAndPermissionsCommandValidator _validator = new(); + private readonly UpdateUserRoleAndPermissionsCommandFixture _updateUserRoleAndPermissionsCommandFixture = new(); [Fact] public void Validate_WhenUserIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = new( + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create( Guid.Empty, Guid.NewGuid(), [Guid.NewGuid()]); @@ -39,7 +41,7 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests public void Validate_WhenPermissionsContainEmptyGuid_ShouldHaveValidationError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = new( + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create( Guid.NewGuid(), Guid.NewGuid(), [Guid.Empty, Guid.NewGuid()]); @@ -55,10 +57,10 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests public void Validate_WhenPermissionsIsNull_ShouldNotHaveValidationError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = new( + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create( Guid.NewGuid(), Guid.NewGuid(), - null!); + includePermissions: false); // Act List result = _validator.TestValidate(command); @@ -71,7 +73,7 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests public void Validate_WhenPermissionsIsEmpty_ShouldNotHaveValidationError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = new( + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create( Guid.NewGuid(), Guid.NewGuid(), []); @@ -87,7 +89,7 @@ public class UpdateUserRoleAndPermissionsCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = new( + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create( Guid.NewGuid(), Guid.NewGuid(), [Guid.NewGuid()]); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs index 9b8f07e5..435de5eb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; +using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -17,12 +18,13 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Querie public class GetUserPermissionsQueryValidatorTests { private readonly GetUserPermissionsQueryValidator _validator = new(); + private readonly GetUserPermissionsQueryFixture _getUserPermissionsQueryFixture = new(); [Fact] public void Validate_WhenUserIdIsNull_ShouldHaveValidationError() { // Arrange - GetUserPermissionsQuery query = new(null); + GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create(includeUserId: false); // Act List result = _validator.TestValidate(query); @@ -35,7 +37,7 @@ public class GetUserPermissionsQueryValidatorTests public void Validate_WhenUserIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetUserPermissionsQuery query = new(Guid.Empty); + GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create(Guid.Empty); // Act List result = _validator.TestValidate(query); @@ -48,7 +50,7 @@ public class GetUserPermissionsQueryValidatorTests public void Validate_WhenUserIdIsValid_ShouldNotHaveValidationError() { // Arrange - GetUserPermissionsQuery query = new(Guid.NewGuid()); + GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create(Guid.NewGuid()); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs index 3212ed10..5aa9f6e4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; +using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -17,12 +18,13 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Querie public class GetUserRoleQueryValidatorTests { private readonly GetUserRoleQueryValidator _validator = new(); + private readonly GetUserRoleQueryFixture _getUserRoleQueryFixture = new(); [Fact] public void Validate_WhenUserIdIsNull_ShouldHaveValidationError() { // Arrange - GetUserRoleQuery query = new(null); + GetUserRoleQuery query = _getUserRoleQueryFixture.Create(includeUserId: false); // Act List result = _validator.TestValidate(query); @@ -35,7 +37,7 @@ public class GetUserRoleQueryValidatorTests public void Validate_WhenUserIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetUserRoleQuery query = new(Guid.Empty); + GetUserRoleQuery query = _getUserRoleQueryFixture.Create(Guid.Empty); // Act List result = _validator.TestValidate(query); @@ -48,7 +50,7 @@ public class GetUserRoleQueryValidatorTests public void Validate_WhenUserIdIsValid_ShouldNotHaveValidationError() { // Arrange - GetUserRoleQuery query = new(Guid.NewGuid()); + GetUserRoleQuery query = _getUserRoleQueryFixture.Create(Guid.NewGuid()); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj index 1aad9a82..e36f9955 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs index bd30f269..96a10c88 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common.Pagination; +using Lumina.Contracts.Fixtures.Core.DTO.Common.Pagination; using System.Diagnostics.CodeAnalysis; #endregion @@ -11,11 +12,13 @@ namespace Lumina.Contracts.UnitTests.DTO.Common.Pagination; [ExcludeFromCodeCoverage] public class PaginationDataDtoTests { + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + [Fact] public void CurrentPage_WhenNotSet_ShouldDefaultToOne() { // Arrange - PaginationDataDto sut = new(); + PaginationDataDto sut = _paginationDataDtoFixture.Create(includeCurrentPage: false, includePerPage: false); // Act int currentPage = sut.CurrentPage; @@ -28,7 +31,7 @@ public class PaginationDataDtoTests public void PerPage_WhenNotSet_ShouldDefaultToTwoHundred() { // Arrange - PaginationDataDto sut = new(); + PaginationDataDto sut = _paginationDataDtoFixture.Create(includeCurrentPage: false, includePerPage: false); // Act int perPage = sut.PerPage; @@ -43,7 +46,7 @@ public class PaginationDataDtoTests public void CurrentPage_WhenSettingValueBelowOne_ShouldClampToOne(int value) { // Arrange - PaginationDataDto sut = new(); + PaginationDataDto sut = _paginationDataDtoFixture.Create(includeCurrentPage: false, includePerPage: false); // Act sut.CurrentPage = value; @@ -58,7 +61,7 @@ public class PaginationDataDtoTests public void PerPage_WhenSettingValueBelowOne_ShouldClampToOne(int value) { // Arrange - PaginationDataDto sut = new(); + PaginationDataDto sut = _paginationDataDtoFixture.Create(includeCurrentPage: false, includePerPage: false); // Act sut.PerPage = value; @@ -71,7 +74,7 @@ public class PaginationDataDtoTests public void CurrentPage_WhenSettingValueAboveOne_ShouldPreserveValue() { // Arrange - PaginationDataDto sut = new(); + PaginationDataDto sut = _paginationDataDtoFixture.Create(includeCurrentPage: false, includePerPage: false); // Act sut.CurrentPage = 5; @@ -84,7 +87,7 @@ public class PaginationDataDtoTests public void PerPage_WhenSettingValueAboveOne_ShouldPreserveValue() { // Arrange - PaginationDataDto sut = new(); + PaginationDataDto sut = _paginationDataDtoFixture.Create(includeCurrentPage: false, includePerPage: false); // Act sut.PerPage = 25; diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoTests.cs index 81015d03..537820e1 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoTests.cs @@ -2,6 +2,7 @@ using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; @@ -16,6 +17,8 @@ namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.Book [ExcludeFromCodeCoverage] public class BookMetadataLookupDtoTests { + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + [Fact] public void Constructor_WhenOmittingOptionalParameters_ShouldUseNullDefaults() { @@ -23,7 +26,7 @@ public class BookMetadataLookupDtoTests Guid libraryId = Guid.NewGuid(); // Act - BookMetadataLookupDto sut = new(libraryId, @"/media/books/dune.epub"); + BookMetadataLookupDto sut = _bookMetadataLookupDtoFixture.Create(libraryId: libraryId, path: @"/media/books/dune.epub"); // Assert Assert.Equal(libraryId, sut.LibraryId); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceDataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceDataDtoTests.cs index bc6d8a34..d044f995 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceDataDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceDataDtoTests.cs @@ -13,7 +13,7 @@ namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.Book [ExcludeFromCodeCoverage] public class ReadingResourceDataDtoTests { - private readonly ReadingResourceDataDtoFixture _fixture = new(); + private readonly ReadingResourceDataDtoFixture _readingResourceDataDtoFixture = new(); [Fact] public void Create_WhenProvidedData_ShouldPreserveIt() @@ -22,7 +22,7 @@ public class ReadingResourceDataDtoTests byte[] data = Guid.NewGuid().ToByteArray(); // Act - ReadingResourceDataDto sut = _fixture.Create(data: data); + ReadingResourceDataDto sut = _readingResourceDataDtoFixture.Create(data: data); // Assert Assert.Equal(data, sut.Data); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Lumina.Contracts.UnitTests.csproj b/tests/UnitTests/Lumina.Contracts.UnitTests/Lumina.Contracts.UnitTests.csproj index 979fb32c..617063e2 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Lumina.Contracts.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Lumina.Contracts.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs index 1e1c75a9..2c762e55 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using System.Diagnostics.CodeAnalysis; #endregion @@ -11,11 +12,13 @@ namespace Lumina.Contracts.UnitTests.Requests.Authentication; [ExcludeFromCodeCoverage] public class RegistrationRequestTests { + private readonly RegistrationRequestFixture _registrationRequestFixture = new(); + [Fact] public void Constructor_WhenOmittingUse2fa_ShouldDefaultToTrue() { // Act - RegistrationRequest sut = new(Username: "user1", Password: "pass1", PasswordConfirm: "pass1"); + RegistrationRequest sut = _registrationRequestFixture.Create(username: "user1", password: "pass1", passwordConfirm: "pass1", use2fa: true); // Assert Assert.True(sut.Use2fa); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs index 0d589fe8..9d302ac6 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; #endregion @@ -11,11 +12,13 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class AddRoleRequestTests { + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + [Fact] public void Constructor_WhenPassingNullPermissions_ShouldReturnNullPermissions() { // Act - AddRoleRequest sut = new(RoleName: "Admin", Permissions: null); + AddRoleRequest sut = _addRoleRequestFixture.Create(roleName: "Admin", includePermissions: false); // Assert Assert.Null(sut.Permissions); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs index 6aa9a43d..d4a46e65 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; #endregion @@ -11,11 +12,13 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class DeleteRoleRequestTests { + private readonly DeleteRoleRequestFixture _deleteRoleRequestFixture = new(); + [Fact] public void Constructor_WhenPassingNullRoleId_ShouldReturnNullRoleId() { // Act - DeleteRoleRequest sut = new(RoleId: null); + DeleteRoleRequest sut = _deleteRoleRequestFixture.Create(includeRoleId: false); // Assert Assert.Null(sut.RoleId); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs index b8c04302..a92b9a37 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; #endregion @@ -11,11 +12,13 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class GetAuthorizationRequestTests { + private readonly GetAuthorizationRequestFixture _getAuthorizationRequestFixture = new(); + [Fact] public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId() { // Act - GetAuthorizationRequest sut = new(UserId: null); + GetAuthorizationRequest sut = _getAuthorizationRequestFixture.Create(includeUserId: false); // Assert Assert.Null(sut.UserId); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs index f8c30af2..9e23abd1 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; #endregion @@ -11,11 +12,13 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class GetUserPermissionsRequestTests { + private readonly GetUserPermissionsRequestFixture _getUserPermissionsRequestFixture = new(); + [Fact] public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId() { // Act - GetUserPermissionsRequest sut = new(UserId: null); + GetUserPermissionsRequest sut = _getUserPermissionsRequestFixture.Create(includeUserId: false); // Assert Assert.Null(sut.UserId); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs index 29dafa4b..5b9e0149 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; #endregion @@ -11,11 +12,13 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class GetUserRoleRequestTests { + private readonly GetUserRoleRequestFixture _getUserRoleRequestFixture = new(); + [Fact] public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId() { // Act - GetUserRoleRequest sut = new(UserId: null); + GetUserRoleRequest sut = _getUserRoleRequestFixture.Create(includeUserId: false); // Assert Assert.Null(sut.UserId); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs index 6df434f1..c23571f8 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Diagnostics.CodeAnalysis; #endregion @@ -11,11 +12,13 @@ namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Common; [ExcludeFromCodeCoverage] public class FileSystemTreeNodeResponseTests { + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture = new(); + [Fact] public void Constructor_WhenInstantiatingNode_ShouldInitializeEmptyChildren() { // Act - FileSystemTreeNodeResponse sut = new(); + FileSystemTreeNodeResponse sut = _fileSystemTreeNodeResponseFixture.Create(maxDepth: 0); // Assert Assert.NotNull(sut.Children); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/AlbumConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/AlbumConfigurationTests.cs index 56797eba..d156dab8 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/AlbumConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/AlbumConfigurationTests.cs @@ -70,11 +70,11 @@ public class AlbumConfigurationTests : IDisposable IProperty originalTitleProperty = entityType.GetProperty(nameof(AlbumEntity.OriginalTitle)); IProperty descriptionProperty = entityType.GetProperty(nameof(AlbumEntity.Description)); IProperty releaseCountryProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseCountry)); - IProperty releaseTypeProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseType)); + IProperty releaseTypeProperty = entityType.FindNavigation(nameof(AlbumEntity.ReleaseTypes))!.TargetEntityType.GetProperty(nameof(AlbumReleaseTypeEntity.ReleaseType)); IProperty releaseStatusProperty = entityType.GetProperty(nameof(AlbumEntity.ReleaseStatus)); IProperty mediaFormatProperty = entityType.GetProperty(nameof(AlbumEntity.MediaFormat)); IProperty barcodeProperty = entityType.GetProperty(nameof(AlbumEntity.Barcode)); - IProperty catalogNumberProperty = entityType.GetProperty(nameof(AlbumEntity.CatalogNumber)); + IProperty catalogNumberProperty = entityType.FindNavigation(nameof(AlbumEntity.CatalogNumbers))!.TargetEntityType.GetProperty(nameof(AlbumCatalogNumberEntity.CatalogNumber)); IProperty languageCodeProperty = entityType.GetProperty(nameof(AlbumEntity.LanguageCode)); // Assert @@ -87,7 +87,7 @@ public class AlbumConfigurationTests : IDisposable Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType); Assert.Equal("TEXT", releaseCountryProperty.GetColumnType()); Assert.Equal(2, releaseCountryProperty.GetMaxLength()); - Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType); + Assert.Equal(typeof(MusicReleaseType), releaseTypeProperty.ClrType); Assert.Equal("TEXT", releaseTypeProperty.GetColumnType()); Assert.Equal(50, releaseTypeProperty.GetMaxLength()); Assert.Equal(typeof(MusicReleaseStatus?), releaseStatusProperty.ClrType); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/BookConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/BookConfigurationTests.cs index 9b6a2766..0e44873b 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/BookConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/BookConfigurationTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs index 4fc59370..c6e51715 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using System; using System.Collections.Generic; @@ -28,6 +29,11 @@ public class LibraryConfigurationTests _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); } + /// + /// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits. + /// + private IModel DesignTimeModel => _context.GetService().Model; + [Fact] public void Configure_WhenApplied_ShouldSetTableNameAndKey() { @@ -64,6 +70,22 @@ public class LibraryConfigurationTests Assert.Equal(true, downloadMetadataProperty.GetDefaultValue()); } + [Fact] + public void Configure_WhenApplied_ShouldConfigurePathTemplateFingerprint() + { + // Arrange + IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!; + + // Act + IProperty fingerprintProperty = entityType.GetProperty(nameof(LibraryEntity.PathTemplateFingerprint)); + + // Assert + Assert.True(fingerprintProperty.IsNullable); + Assert.Equal(typeof(string), fingerprintProperty.ClrType); + Assert.Equal(64, fingerprintProperty.GetMaxLength()); + Assert.Equal(11, fingerprintProperty.GetColumnOrder()); + } + [Fact] public void Configure_WhenApplied_ShouldConfigureOwnedContentLocations() { @@ -71,15 +93,78 @@ public class LibraryConfigurationTests IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!; // Act - List ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)]; + IEntityType contentLocationType = Assert.Single( + _context.Model.GetEntityTypes(), + ownedType => ownedType.IsOwned() + && ownedType.ClrType == typeof(LibraryContentLocationEntity) + && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name); // Assert - IEntityType contentLocationType = Assert.Single(ownedTypes); Assert.Equal(typeof(LibraryContentLocationEntity), contentLocationType.ClrType); Assert.Equal("LibraryContentLocations", contentLocationType.GetTableName()); Assert.Equal(260, contentLocationType.GetProperty(nameof(LibraryContentLocationEntity.Path)).GetMaxLength()); } + [Fact] + public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplateParts() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!; + + // Act + IEntityType partEntityType = Assert.Single( + _context.Model.GetEntityTypes(), + ownedType => ownedType.IsOwned() + && ownedType.ClrType == typeof(LibraryPathTemplatePartEntity) + && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name); + IForeignKey ownershipForeignKey = partEntityType.FindOwnership()!; + + // Assert + Assert.Equal("LibraryPathTemplateParts", partEntityType.GetTableName()); + Assert.Equal(["Id"], partEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name)); + + Assert.Equal(typeof(LibraryEntity), ownershipForeignKey.PrincipalEntityType.ClrType); + Assert.Equal(["LibraryId"], ownershipForeignKey.Properties.Select(property => property.Name)); + Assert.True(ownershipForeignKey.IsRequired); + + IIndex uniqueIndex = Assert.Single( + partEntityType.GetIndexes(), + index => index.Properties.Select(property => property.Name).SequenceEqual(["LibraryId", nameof(LibraryPathTemplatePartEntity.Position)])); + Assert.True(uniqueIndex.IsUnique); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplatePartColumns() + { + // Arrange + IEntityType partEntityType = DesignTimeModel.GetEntityTypes() + .Single(entityType => entityType.IsOwned() + && entityType.ClrType == typeof(LibraryPathTemplatePartEntity) + && entityType.GetTableName() == "LibraryPathTemplateParts"); + + // Act + IProperty positionProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Position)); + IProperty kindProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Kind)); + IProperty representationProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Representation)); + IProperty isOptionalProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.IsOptional)); + + // Assert + Assert.Equal("Position", positionProperty.GetColumnName()); + Assert.False(positionProperty.IsNullable); + + Assert.Equal(typeof(LibraryPathPartKind), kindProperty.ClrType); + Assert.Equal(typeof(string), kindProperty.GetTypeMapping().Converter!.ProviderClrType); + Assert.Equal("TEXT", kindProperty.GetColumnType()); + Assert.Equal(32, kindProperty.GetMaxLength()); + Assert.False(kindProperty.IsNullable); + + Assert.Equal(512, representationProperty.GetMaxLength()); + Assert.False(representationProperty.IsNullable); + + Assert.Equal(typeof(bool), isOptionalProperty.ClrType); + Assert.False(isOptionalProperty.IsNullable); + } + [Fact] public void Configure_WhenApplied_ShouldConfigureRelationships() { @@ -111,4 +196,23 @@ public class LibraryConfigurationTests Assert.False(createdOnUtcProperty.IsNullable); Assert.Null(updatedOnUtcProperty.GetDefaultValue()); } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditColumnOrders() + { + // Arrange + IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedBy)); + + // Assert + Assert.Equal(12, createdOnUtcProperty.GetColumnOrder()); + Assert.Equal(13, createdByProperty.GetColumnOrder()); + Assert.Equal(14, updatedOnUtcProperty.GetColumnOrder()); + Assert.Equal(15, updatedByProperty.GetColumnOrder()); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicArtworkConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicArtworkConfigurationTests.cs new file mode 100644 index 00000000..6987317f --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicArtworkConfigurationTests.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkConfigurationTests : IDisposable +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("MusicArtwork", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValue() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + IProperty ownerTypeProperty = entityType.GetProperty(nameof(MusicArtworkEntity.OwnerType)); + IProperty ownerIdProperty = entityType.GetProperty(nameof(MusicArtworkEntity.OwnerId)); + IProperty artworkTypeProperty = entityType.GetProperty(nameof(MusicArtworkEntity.ArtworkType)); + IProperty ordinalProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Ordinal)); + IProperty fileNameProperty = entityType.GetProperty(nameof(MusicArtworkEntity.FileName)); + IProperty contentHashProperty = entityType.GetProperty(nameof(MusicArtworkEntity.ContentHash)); + IProperty statusProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Status)); + IProperty providerProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Provider)); + IProperty lastUpdateUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.LastUpdateUtc)); + + // Assert + Assert.False(ownerTypeProperty.IsNullable); + Assert.Equal(typeof(MusicArtworkOwnerType), ownerTypeProperty.ClrType); + Assert.Equal("TEXT", ownerTypeProperty.GetColumnType()); + Assert.Equal(50, ownerTypeProperty.GetMaxLength()); + Assert.False(ownerIdProperty.IsNullable); + Assert.False(artworkTypeProperty.IsNullable); + Assert.Equal(typeof(ArtworkType), artworkTypeProperty.ClrType); + Assert.Equal("TEXT", artworkTypeProperty.GetColumnType()); + Assert.Equal(50, artworkTypeProperty.GetMaxLength()); + Assert.False(ordinalProperty.IsNullable); + Assert.True(fileNameProperty.IsNullable); + Assert.Equal(2048, fileNameProperty.GetMaxLength()); + Assert.False(contentHashProperty.IsNullable); + Assert.False(statusProperty.IsNullable); + Assert.Equal(typeof(ArtworkStatus), statusProperty.ClrType); + Assert.Equal("TEXT", statusProperty.GetColumnType()); + Assert.Equal(20, statusProperty.GetMaxLength()); + Assert.True(providerProperty.IsNullable); + Assert.Equal(100, providerProperty.GetMaxLength()); + Assert.True(lastUpdateUtcProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueOwnerArtworkIndex() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + IIndex uniqueIndex = Assert.Single(indexes, index => index.IsUnique); + Assert.Equal( + [nameof(MusicArtworkEntity.OwnerType), nameof(MusicArtworkEntity.OwnerId), nameof(MusicArtworkEntity.ArtworkType), nameof(MusicArtworkEntity.Ordinal)], + uniqueIndex.Properties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexOnStatus() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(MusicArtworkEntity.Status)])); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(MusicArtworkEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(MusicArtworkEntity.UpdatedBy)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.False(createdByProperty.IsNullable); + Assert.True(updatedOnUtcProperty.IsNullable); + Assert.True(updatedByProperty.IsNullable); + } + + /// + /// Disposes the database context. + /// + public void Dispose() + { + _context.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicLibraryScanItemMetadataConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicLibraryScanItemMetadataConfigurationTests.cs new file mode 100644 index 00000000..9a7b6d52 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicLibraryScanItemMetadataConfigurationTests.cs @@ -0,0 +1,163 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryScanItemMetadataConfigurationTests : IDisposable +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public MusicLibraryScanItemMetadataConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("MusicLibraryScanItemMetadata", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValue() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRequiredScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!; + + // Act + IProperty libraryScanIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.LibraryScanId)); + IProperty libraryIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.LibraryId)); + IProperty pathProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Path)); + + // Assert + Assert.False(libraryScanIdProperty.IsNullable); + Assert.False(libraryIdProperty.IsNullable); + Assert.False(pathProperty.IsNullable); + Assert.Equal(2048, pathProperty.GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureOptionalScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!; + + // Act + IProperty artistNameProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ArtistName)); + IProperty releaseTypeProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseType)); + IProperty releaseYearProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseYear)); + IProperty releaseNameProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReleaseName)); + IProperty trackTitleProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.TrackTitle)); + IProperty audioCodecProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.AudioCodec)); + IProperty workTitleProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.WorkTitle)); + IProperty acoustIdProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.AcoustId)); + + // Assert + Assert.True(artistNameProperty.IsNullable); + Assert.Equal(255, artistNameProperty.GetMaxLength()); + Assert.True(releaseTypeProperty.IsNullable); + Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType); + Assert.Equal("TEXT", releaseTypeProperty.GetColumnType()); + Assert.Equal(50, releaseTypeProperty.GetMaxLength()); + Assert.True(releaseYearProperty.IsNullable); + Assert.Equal(255, releaseNameProperty.GetMaxLength()); + Assert.Equal(255, trackTitleProperty.GetMaxLength()); + Assert.Equal(50, audioCodecProperty.GetMaxLength()); + Assert.Equal(255, workTitleProperty.GetMaxLength()); + Assert.Equal(64, acoustIdProperty.GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureReplayGainDecimalPrecision() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!; + + // Act + IProperty trackGainProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainTrackGain)); + IProperty trackPeakProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainTrackPeak)); + IProperty albumGainProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainAlbumGain)); + IProperty albumPeakProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.ReplayGainAlbumPeak)); + + // Assert + Assert.Equal("decimal(8,2)", trackGainProperty.GetColumnType()); + Assert.Equal("decimal(8,6)", trackPeakProperty.GetColumnType()); + Assert.Equal("decimal(8,2)", albumGainProperty.GetColumnType()); + Assert.Equal("decimal(8,6)", albumPeakProperty.GetColumnType()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureMoodsAsPrimitiveCollection() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!; + + // Act + IProperty moodsProperty = entityType.GetProperty(nameof(MusicLibraryScanItemMetadataEntity.Moods)); + + // Assert + Assert.True(moodsProperty.IsPrimitiveCollection); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueScanIdPathIndex() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicLibraryScanItemMetadataEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + IIndex uniqueIndex = Assert.Single(indexes, index => index.IsUnique); + Assert.Equal( + [nameof(MusicLibraryScanItemMetadataEntity.LibraryScanId), nameof(MusicLibraryScanItemMetadataEntity.Path)], + uniqueIndex.Properties.Select(property => property.Name)); + } + + /// + /// Disposes the database context. + /// + public void Dispose() + { + _context.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackConfigurationTests.cs index 2cbb25e2..87c6a673 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackConfigurationTests.cs @@ -72,7 +72,7 @@ public class TrackConfigurationTests : IDisposable IProperty scriptProperty = entityType.GetProperty(nameof(TrackEntity.Script)); IProperty keyProperty = entityType.GetProperty(nameof(TrackEntity.Key)); IProperty audioCodecProperty = entityType.GetProperty(nameof(TrackEntity.AudioCodec)); - IProperty workProperty = entityType.GetProperty(nameof(TrackEntity.Work)); + IProperty workProperty = entityType.GetProperty(nameof(TrackEntity.WorkTitle)); // Assert Assert.False(pathProperty.IsNullable); @@ -118,9 +118,11 @@ public class TrackConfigurationTests : IDisposable List ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)]; // Assert - Assert.Equal(3, ownedTypes.Count); + Assert.Equal(5, ownedTypes.Count); Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackMoodEntity) && ownedType.GetTableName() == "TrackMoods"); Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackIsrcEntity) && ownedType.GetTableName() == "TrackIsrcs"); + Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackWorkLanguageEntity) && ownedType.GetTableName() == "TrackWorkLanguages"); + Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(TrackWorkIswcEntity) && ownedType.GetTableName() == "TrackWorkIswcs"); Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(AudioRatingEntity) && ownedType.GetTableName() == "TrackRatings"); } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs index c4375abc..709ccecd 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -314,6 +314,74 @@ public class BookRepositoryTests Assert.Null(result.Value); } + [Fact] + public async Task GetExistingPathsAsync_WhenPathsIsEmpty_ShouldReturnAnEmptyCollection() + { + // Arrange + IReadOnlyCollection paths = []; + + // Act + Result> result = await _sut.GetExistingPathsAsync(Guid.NewGuid(), paths, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenCalled_ShouldReturnOnlyThePathsUsedByBooksOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity bookOfLibrary = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/tolkien/the-hobbit.epub"); + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/books/tolkien/the-lord-of-the-rings.epub"); + _mockContext.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub", "/books/tolkien/the-lord-of-the-rings.epub"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + string existingPath = Assert.Single(result.Value); + Assert.Equal("/books/tolkien/the-hobbit.epub", existingPath); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenInputContainsDuplicatePaths_ShouldDeDuplicateTheResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/tolkien/the-hobbit.epub"); + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub", "/books/tolkien/the-hobbit.epub", "/books/tolkien/the-hobbit.epub"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal("/books/tolkien/the-hobbit.epub", result.Value.First()); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenPathDiffersOnlyByCase_ShouldNotReportItAsExisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: "/Books/Tolkien/The-Hobbit.epub"); + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/tolkien/the-hobbit.epub"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + [Fact] public async Task GetBooksNeedingMetadataAsync_WhenCalled_ShouldReturnOnlyBooksWhoseMetadataIsNotEnriched() { diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs index 7c44ef48..0ecb39fb 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs @@ -8,6 +8,7 @@ using Lumina.DataAccess.Core.Repositories.Libraries; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -29,6 +30,7 @@ public class LibraryRepositoryTests private readonly LuminaDbContext _mockContext; private readonly LibraryRepository _sut; private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -230,4 +232,307 @@ public class LibraryRepositoryTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); } + + [Fact] + public async Task InsertAsync_WhenLibraryHasPathTemplateParts_ShouldAddLibraryAndItsPartsToContext() + { + // Arrange + LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Separator, representation: "/", isOptional: false); + LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true); + LibraryEntity library = _libraryEntityFixture.Create( + contentLocations: [], + pathTemplateParts: [firstPart, secondPart, thirdPart], + pathTemplateFingerprint: "path-template-fingerprint"); + + // Act + Result result = await _sut.InsertAsync(library, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedLibrary = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == library.Id); + Assert.NotNull(addedLibrary); + Assert.Equal("path-template-fingerprint", addedLibrary!.Entity.PathTemplateFingerprint); + + List> partEntries = [.. _mockContext.ChangeTracker.Entries() + .Where(entityEntry => entityEntry.State == EntityState.Added)]; + Assert.Equal(3, partEntries.Count); + Assert.Equal([0, 1, 2], partEntries.Select(entityEntry => entityEntry.Entity.Position).OrderBy(position => position)); + + LibraryPathTemplatePartEntity storedFirstPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 0).Entity; + Assert.Equal(LibraryPathPartKind.Artist, storedFirstPart.Kind); + Assert.Equal("{0}", storedFirstPart.Representation); + Assert.False(storedFirstPart.IsOptional); + + LibraryPathTemplatePartEntity storedSecondPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 1).Entity; + Assert.Equal(LibraryPathPartKind.Separator, storedSecondPart.Kind); + Assert.Equal("/", storedSecondPart.Representation); + Assert.False(storedSecondPart.IsOptional); + + LibraryPathTemplatePartEntity storedThirdPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 2).Entity; + Assert.Equal(LibraryPathPartKind.Series, storedThirdPart.Kind); + Assert.Equal("{0}", storedThirdPart.Representation); + Assert.True(storedThirdPart.IsOptional); + } + + [Fact] + public async Task UpdateAsync_WhenPathTemplatePartRepresentationChanges_ShouldReplaceThatPart() + { + // Arrange + LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false); + LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{1}", isOptional: false); + LibraryEntity updatedLibrary = _libraryEntityFixture.Create( + id: library.Id, + userId: library.UserId, + contentLocations: [], + pathTemplateParts: [keptPart, replacementPart]); + + // Act + Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? replacedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart)); + Assert.NotNull(replacedEntry); + Assert.Equal(EntityState.Deleted, replacedEntry!.State); + + EntityEntry? keptEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, keptPart)); + Assert.NotNull(keptEntry); + Assert.Equal(EntityState.Unchanged, keptEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + Assert.False(retrievedResult.IsFailure); + LibraryEntity retrievedLibrary = Assert.IsType(retrievedResult.Value); + Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count); + Assert.Equal("{0}", retrievedLibrary.PathTemplateParts.Single(part => part.Position == 0).Representation); + Assert.Equal("{1}", retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).Representation); + } + + [Fact] + public async Task UpdateAsync_WhenPathTemplatePartKindChanges_ShouldReplaceThatPart() + { + // Arrange + LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false); + LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: false); + LibraryEntity updatedLibrary = _libraryEntityFixture.Create( + id: library.Id, + userId: library.UserId, + contentLocations: [], + pathTemplateParts: [keptPart, replacementPart]); + + // Act + Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? replacedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart)); + Assert.NotNull(replacedEntry); + Assert.Equal(EntityState.Deleted, replacedEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(retrievedResult.Value); + Assert.Equal(LibraryPathPartKind.Series, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).Kind); + } + + [Fact] + public async Task UpdateAsync_WhenPathTemplatePartIsOptionalChanges_ShouldReplaceThatPart() + { + // Arrange + LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: false); + LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true); + LibraryEntity updatedLibrary = _libraryEntityFixture.Create( + id: library.Id, + userId: library.UserId, + contentLocations: [], + pathTemplateParts: [keptPart, replacementPart]); + + // Act + Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? replacedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart)); + Assert.NotNull(replacedEntry); + Assert.Equal(EntityState.Deleted, replacedEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(retrievedResult.Value); + Assert.True(retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).IsOptional); + } + + [Fact] + public async Task UpdateAsync_WhenPathTemplatePartPositionIsRemoved_ShouldRemoveThatPart() + { + // Arrange + LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity removedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true); + LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, removedPart, thirdPart]); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + LibraryEntity updatedLibrary = _libraryEntityFixture.Create( + id: library.Id, + userId: library.UserId, + contentLocations: [], + pathTemplateParts: [firstPart, thirdPart]); + + // Act + Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? removedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, removedPart)); + Assert.NotNull(removedEntry); + Assert.Equal(EntityState.Deleted, removedEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(retrievedResult.Value); + Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count); + Assert.Equal([0, 2], retrievedLibrary.PathTemplateParts.Select(part => part.Position).OrderBy(position => position)); + } + + [Fact] + public async Task UpdateAsync_WhenPathTemplatePartPositionIsAdded_ShouldAddThatPart() + { + // Arrange + LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false); + LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, secondPart]); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + LibraryPathTemplatePartEntity addedPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true); + LibraryEntity updatedLibrary = _libraryEntityFixture.Create( + id: library.Id, + userId: library.UserId, + contentLocations: [], + pathTemplateParts: [firstPart, secondPart, addedPart]); + + // Act + Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? addedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, addedPart)); + Assert.NotNull(addedEntry); + Assert.Equal(EntityState.Added, addedEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(retrievedResult.Value); + Assert.Equal(3, retrievedLibrary.PathTemplateParts.Count); + Assert.Equal([0, 1, 2], retrievedLibrary.PathTemplateParts.Select(part => part.Position).OrderBy(position => position)); + + LibraryPathTemplatePartEntity storedAddedPart = retrievedLibrary.PathTemplateParts.Single(part => part.Position == 2); + Assert.Equal(LibraryPathPartKind.Series, storedAddedPart.Kind); + Assert.Equal("{0}", storedAddedPart.Representation); + Assert.True(storedAddedPart.IsOptional); + } + + [Fact] + public async Task UpdateAsync_WhenPathTemplatePartsAreUnchanged_ShouldKeepExistingParts() + { + // Arrange + LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false); + LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, secondPart]); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + LibraryPathTemplatePartEntity equivalentFirstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity equivalentSecondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false); + LibraryEntity updatedLibrary = _libraryEntityFixture.Create( + id: library.Id, + userId: library.UserId, + contentLocations: [], + pathTemplateParts: [equivalentFirstPart, equivalentSecondPart]); + + // Act + Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + Assert.DoesNotContain( + _mockContext.ChangeTracker.Entries(), + entityEntry => entityEntry.State == EntityState.Added || entityEntry.State == EntityState.Deleted); + + EntityEntry? firstEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, firstPart)); + Assert.NotNull(firstEntry); + Assert.Equal(EntityState.Unchanged, firstEntry!.State); + + EntityEntry? secondEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, secondPart)); + Assert.NotNull(secondEntry); + Assert.Equal(EntityState.Unchanged, secondEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(retrievedResult.Value); + Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count); + Assert.Same(firstPart, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 0)); + Assert.Same(secondPart, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1)); + } + + [Fact] + public async Task UpdateAsync_WhenPathTemplateFingerprintChanges_ShouldUpdateIt() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [], pathTemplateFingerprint: "old-fingerprint"); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + LibraryEntity updatedLibrary = _libraryEntityFixture.Create( + id: library.Id, + userId: library.UserId, + contentLocations: [], + pathTemplateParts: [], + pathTemplateFingerprint: "new-fingerprint"); + + // Act + Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + LibraryEntity? retrievedLibrary = await _mockContext.Libraries.FindAsync(library.Id); + Assert.NotNull(retrievedLibrary); + Assert.Equal("new-fingerprint", retrievedLibrary!.PathTemplateFingerprint); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs index 641fa0b8..1e3ec47a 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.DataAccess.Core.Repositories.MediaContributors; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -91,6 +92,42 @@ public class MediaContributorRepositoryTests Assert.Single(_mockContext.ChangeTracker.Entries()); } + [Fact] + public async Task FindOrCreateByDisplayNameAsync_WhenExistingNameStartsWithNonAsciiUppercase_ShouldReturnTheExistingContributor() + { + // Arrange + // The storage medium folds only ASCII case, so a name starting with a non-ASCII uppercase letter would previously not be found by the lookup + // and would be inserted again, violating the unique index on the display name. + MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Лев Ошанин"); + _mockContext.MediaContributors.Add(existingContributor); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.FindOrCreateByDisplayNameAsync("Лев Ошанин", null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(existingContributor.Id, result.Value.Id); + Assert.Single(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task FindOrCreateByDisplayNameAsync_WhenContributorWasAddedButNotSaved_ShouldReturnTheTrackedContributor() + { + // Arrange + Result firstResult = await _sut.FindOrCreateByDisplayNameAsync("Bob Ludwig", null, CancellationToken.None); + Assert.False(firstResult.IsFailure); + + // Act + Result secondResult = await _sut.FindOrCreateByDisplayNameAsync("BOB LUDWIG", null, CancellationToken.None); + + // Assert + Assert.False(secondResult.IsFailure); + // The contributor added earlier in the same unit of work is tracked, so it is returned instead of a duplicate being added. + Assert.Equal(firstResult.Value.Id, secondResult.Value.Id); + Assert.Single(_mockContext.ChangeTracker.Entries(), entityEntry => entityEntry.State == EntityState.Added); + } + [Fact] public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheContributorsWithTheProvidedIds() { @@ -128,4 +165,21 @@ public class MediaContributorRepositoryTests .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == contributor.Id); Assert.NotNull(addedContributor); } + + [Fact] + public async Task InsertAsync_WhenContributorWithSameIdAlreadyExists_ShouldReturnError() + { + // Arrange + MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(); + _mockContext.MediaContributors.Add(existingContributor); + await _mockContext.SaveChangesAsync(); + MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(id: existingContributor.Id); + + // Act + Result result = await _sut.InsertAsync(contributor, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorAlreadyExists, result.FirstError); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs index 23b27f7d..0666fcf4 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs @@ -14,6 +14,7 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using NSubstitute; @@ -499,6 +500,32 @@ public class AlbumRepositoryTests Assert.Single(_mockContext.Set().Where(genre => genre.Name == "ExistingGenre")); } + [Fact] + public async Task UpdateAsync_WhenCatalogNumbersChange_ShouldAddTheNewAndRemoveTheMissingOnes() + { + // Arrange + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, catalogNumbers: ["EMC 3006", "OC 062 o 94519"]); + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false, catalogNumbers: ["EMC 3006", "EMTC 104"]); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity? retrievedAlbum = await _mockContext.Albums + .Include(album => album.CatalogNumbers) + .FirstOrDefaultAsync(album => album.Id == storedAlbum.Id); + Assert.NotNull(retrievedAlbum); + Assert.Equal(2, retrievedAlbum!.CatalogNumbers.Count); + Assert.Contains(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "EMC 3006"); + Assert.Contains(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "EMTC 104"); + Assert.DoesNotContain(retrievedAlbum.CatalogNumbers, catalogNumber => catalogNumber.CatalogNumber == "OC 062 o 94519"); + } + [Fact] public async Task GetByIdAsync_WhenAlbumExists_ShouldReturnTheAlbum() { @@ -714,6 +741,26 @@ public class AlbumRepositoryTests Assert.Equal(12, row.TotalTracks); } + [Fact] + public async Task GetAlbumsNeedingMetadataCountAsync_WhenAlbumsHaveMixedMetadataStatuses_ShouldCountOnlyTheNotEnrichedOnesOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity pendingAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + AlbumEntity failedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Failed); + AlbumEntity enrichedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Enriched); + AlbumEntity albumOfAnotherLibrary = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + _mockContext.Albums.AddRange(pendingAlbum, failedAlbum, enrichedAlbum, albumOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetAlbumsNeedingMetadataCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value); + } + /// /// Creates an album that belongs to the artist identified by , with every related collection populated deterministically. /// diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs index add56a0c..38dd1bf3 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs @@ -16,6 +16,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -1118,6 +1119,104 @@ public class ArtistRepositoryTests Assert.Equal(expectedRowCount, page.Data.Count); } + [Fact] + public async Task GetArtistsNeedingMetadataAsync_WhenAnArtistAndAllItsDescendantsAreEnriched_ShouldNotReturnIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity enriched = CreateArtistWithFullAggregate(); + enriched.LibraryId = libraryId; + MarkEnriched(enriched); + ArtistEntity pending = _artistEntityFixture.Create(libraryId: libraryId, name: "Pending Artist", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(enriched, pending); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity onlyArtist = Assert.Single(result.Value); + Assert.Equal(pending.Id, onlyArtist.Id); + } + + [Fact] + public async Task GetArtistsNeedingMetadataAsync_WhenATrackIsNotEnriched_ShouldReturnTheArtist() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = CreateArtistWithFullAggregate(); + artist.LibraryId = libraryId; + MarkEnriched(artist); + artist.Albums[0].Tracks[0].MetadataStatus = MetadataStatus.Pending; + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity onlyArtist = Assert.Single(result.Value); + Assert.Equal(artist.Id, onlyArtist.Id); + } + + [Fact] + public async Task GetArtistsNeedingMetadataAsync_WhenLastNameIsProvided_ShouldReturnOnlyArtistsAfterIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity alpha = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity beta = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + ArtistEntity gamma = _artistEntityFixture.Create(libraryId: libraryId, name: "Gamma", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(alpha, beta, gamma); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetArtistsNeedingMetadataAsync(libraryId, "Beta", 10, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity onlyArtist = Assert.Single(result.Value); + Assert.Equal(gamma.Id, onlyArtist.Id); + } + + [Fact] + public async Task GetArtistsNeedingMetadataCountAsync_ShouldCountArtistsWithPendingMetadataIncludingDescendants() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity enriched = CreateArtistWithFullAggregate(); + enriched.LibraryId = libraryId; + MarkEnriched(enriched); + ArtistEntity pending = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity otherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(enriched, pending, otherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetArtistsNeedingMetadataCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value); + } + + /// + /// Marks the provided artist, its albums and its tracks as enriched. + /// + /// The artist whose metadata enrichment status is set. + private static void MarkEnriched(ArtistEntity artist) + { + artist.MetadataStatus = MetadataStatus.Enriched; + foreach (AlbumEntity album in artist.Albums) + { + album.MetadataStatus = MetadataStatus.Enriched; + foreach (TrackEntity track in album.Tracks) + track.MetadataStatus = MetadataStatus.Enriched; + } + } + /// /// Creates an artist that owns an album which in turn owns a track, with every related collection of the aggregate populated deterministically. /// diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicArtworkRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicArtworkRepositoryTests.cs new file mode 100644 index 00000000..4fb1496f --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicArtworkRepositoryTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkRepositoryTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly LuminaDbContext _context; + private readonly MusicArtworkRepository _sut; + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkRepositoryTests() + { + // the repository deletes and updates in bulk, which translates to SQL, so it can only be exercised against a real SQLite database + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connection).Options); + _context.Database.EnsureCreated(); + _sut = new MusicArtworkRepository(_context); + } + + [Fact] + public async Task InsertRangeAsync_WhenCalledWithArtwork_ShouldAddThemToContextAndReturnCreated() + { + // Arrange + List artwork = _musicArtworkEntityFixture.CreateMany(3); + + // Act + Result result = await _sut.InsertRangeAsync(artwork, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + await _context.SaveChangesAsync(); + Assert.Equal(3, await _context.MusicArtwork.CountAsync()); + } + + [Fact] + public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutAddingAnyArtwork() + { + // Act + Result result = await _sut.InsertRangeAsync([], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + await _context.SaveChangesAsync(); + Assert.Empty(await _context.MusicArtwork.ToListAsync()); + } + + [Fact] + public async Task GetByOwnerAsync_WhenCalled_ShouldReturnOnlyTheArtworkOfTheOwnerOrderedByTypeThenOrdinal() + { + // Arrange + MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album; + Guid ownerId = Guid.NewGuid(); + MusicArtworkEntity frontSecond = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 1); + MusicArtworkEntity frontFirst = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 0); + MusicArtworkEntity cover = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0); + MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: Guid.NewGuid()); + MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: ownerId); + _context.MusicArtwork.AddRange(frontSecond, frontFirst, cover, artworkOfAnotherOwner, artworkOfAnotherOwnerType); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByOwnerAsync(ownerType, ownerId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([cover.Id, frontFirst.Id, frontSecond.Id], result.Value.Select(artwork => artwork.Id)); + } + + [Fact] + public async Task GetByOwnerAsync_WhenTheOwnerHasNoArtwork_ShouldReturnAnEmptyCollection() + { + // Act + Result> result = await _sut.GetByOwnerAsync(MusicArtworkOwnerType.Track, Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task DeleteByOwnerAsync_WhenCalled_ShouldDeleteOnlyTheArtworkOfTheOwner() + { + // Arrange + MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album; + Guid ownerId = Guid.NewGuid(); + MusicArtworkEntity artworkOfOwner = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId); + MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: Guid.NewGuid()); + MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: ownerId); + _context.MusicArtwork.AddRange(artworkOfOwner, artworkOfAnotherOwner, artworkOfAnotherOwnerType); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByOwnerAsync(ownerType, ownerId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + List remainingArtwork = await _context.MusicArtwork.ToListAsync(); + Assert.Equal(2, remainingArtwork.Count); + Assert.DoesNotContain(remainingArtwork, artwork => artwork.Id == artworkOfOwner.Id); + Assert.Contains(remainingArtwork, artwork => artwork.Id == artworkOfAnotherOwner.Id); + Assert.Contains(remainingArtwork, artwork => artwork.Id == artworkOfAnotherOwnerType.Id); + } + + [Fact] + public async Task DeleteByOwnerAsync_WhenNoArtworkExistsForTheOwner_ShouldReturnDeleted() + { + // Act + Result result = await _sut.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + } + + [Fact] + public async Task ResetStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkOfTheLibraryItemsToPending() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _context.Artists.AddRange(artist, artistOfAnotherLibrary); + _context.Albums.Add(album); + _context.Tracks.Add(track); + MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, status: ArtworkStatus.Enriched); + MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, status: ArtworkStatus.Enriched); + MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, status: ArtworkStatus.Enriched); + MusicArtworkEntity artworkOfAnotherLibrary = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistOfAnotherLibrary.Id, status: ArtworkStatus.Enriched); + _context.MusicArtwork.AddRange(artistArtwork, albumArtwork, trackArtwork, artworkOfAnotherLibrary); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.ResetStatusForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + // the bulk update bypasses the change tracker, so the tracked entities are detached before the stored values are read back + _context.ChangeTracker.Clear(); + Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(artistArtwork.Id))!.Status); + Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(albumArtwork.Id))!.Status); + Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(trackArtwork.Id))!.Status); + Assert.Equal(ArtworkStatus.Enriched, (await _context.MusicArtwork.FindAsync(artworkOfAnotherLibrary.Id))!.Status); + } + + /// + /// Disposes the database context and its underlying connection. + /// + public void Dispose() + { + _context.Dispose(); + _connection.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepositoryTests.cs new file mode 100644 index 00000000..b9c417ed --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepositoryTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryScanItemMetadataRepositoryTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly LuminaDbContext _context; + private readonly MusicLibraryScanItemMetadataRepository _sut; + private readonly MusicLibraryScanItemMetadataEntityFixture _musicLibraryScanItemMetadataEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicLibraryScanItemMetadataRepositoryTests() + { + // the repository deletes in bulk, which translates to SQL, so it can only be exercised against a real SQLite database + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connection).Options); + _context.Database.EnsureCreated(); + _sut = new MusicLibraryScanItemMetadataRepository(_context); + } + + [Fact] + public async Task InsertRangeAsync_WhenCalledWithItems_ShouldAddThemToContextAndReturnCreated() + { + // Arrange + List items = _musicLibraryScanItemMetadataEntityFixture.CreateMany(3); + + // Act + Result result = await _sut.InsertRangeAsync(items, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + await _context.SaveChangesAsync(); + Assert.Equal(3, await _context.MusicLibraryScanItemMetadata.CountAsync()); + } + + [Fact] + public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutAddingAnyItems() + { + // Act + Result result = await _sut.InsertRangeAsync([], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + await _context.SaveChangesAsync(); + Assert.Empty(await _context.MusicLibraryScanItemMetadata.ToListAsync()); + } + + [Fact] + public async Task GetByScanIdAsync_WhenCalled_ShouldReturnOnlyTheItemsOfTheScanOrderedByPath() + { + // Arrange + Guid scanId = Guid.NewGuid(); + MusicLibraryScanItemMetadataEntity bicycleItem = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bicycle-race.flac"); + MusicLibraryScanItemMetadataEntity bohemianItem = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bohemian-rhapsody.flac"); + MusicLibraryScanItemMetadataEntity itemOfAnotherScan = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/dont-stop-me-now.flac"); + _context.MusicLibraryScanItemMetadata.AddRange(bicycleItem, bohemianItem, itemOfAnotherScan); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByScanIdAsync(scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([bicycleItem.Id, bohemianItem.Id], result.Value.Select(item => item.Id)); + } + + [Fact] + public async Task GetByScanIdAsync_WhenNoItemsExistForTheScan_ShouldReturnAnEmptyCollection() + { + // Act + Result> result = await _sut.GetByScanIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task DeleteByScanIdAsync_WhenCalled_ShouldDeleteOnlyTheItemsOfTheScan() + { + // Arrange + Guid scanId = Guid.NewGuid(); + MusicLibraryScanItemMetadataEntity itemOfScan = _musicLibraryScanItemMetadataEntityFixture.Create(libraryScanId: scanId, path: "/music/queen/bohemian-rhapsody.flac"); + MusicLibraryScanItemMetadataEntity itemOfAnotherScan = _musicLibraryScanItemMetadataEntityFixture.Create(path: "/music/queen/love-of-my-life.flac"); + _context.MusicLibraryScanItemMetadata.AddRange(itemOfScan, itemOfAnotherScan); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByScanIdAsync(scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + MusicLibraryScanItemMetadataEntity remainingItem = Assert.Single(await _context.MusicLibraryScanItemMetadata.ToListAsync()); + Assert.Equal(itemOfAnotherScan.Id, remainingItem.Id); + } + + /// + /// Disposes the database context and its underlying connection. + /// + public void Dispose() + { + _context.Dispose(); + _connection.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs index 7b12913e..71a4ab0d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs @@ -13,6 +13,7 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -792,4 +793,24 @@ public class TrackRepositoryTests Assert.Equal(9, row.TrackNumber); Assert.Equal(3, row.DiscNumber); } + + [Fact] + public async Task GetTracksNeedingMetadataCountAsync_WhenTracksHaveMixedMetadataStatuses_ShouldCountOnlyTheNotEnrichedOnesOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + TrackEntity pendingTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + TrackEntity failedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Failed); + TrackEntity enrichedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Enriched); + TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(includeMetadata: false, metadataStatus: MetadataStatus.Pending); + _mockContext.Tracks.AddRange(pendingTrack, failedTrack, enrichedTrack, trackOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetTracksNeedingMetadataCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs index fa8a878a..9526580e 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs @@ -22,7 +22,7 @@ public class ArtworkProviderConfigurationRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly ArtworkProviderConfigurationRepository _sut; - private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -38,8 +38,8 @@ public class ArtworkProviderConfigurationRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); - LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -70,7 +70,7 @@ public class ArtworkProviderConfigurationRepositoryTests public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt() { // Arrange - LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryArtworkProviderConfigurations.Add(configuration); await _mockContext.SaveChangesAsync(); @@ -101,7 +101,7 @@ public class ArtworkProviderConfigurationRepositoryTests public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt() { // Arrange - LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); // Act Result result = await _sut.UpsertAsync(configuration, CancellationToken.None); @@ -116,11 +116,11 @@ public class ArtworkProviderConfigurationRepositoryTests public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt() { // Arrange - LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryArtworkProviderConfigurations.Add(configuration); await _mockContext.SaveChangesAsync(); - LibraryArtworkProviderConfigurationEntity updatedConfiguration = _configurationFixture.Create(configuration.LibraryId, configuration.PluginId, 5); + LibraryArtworkProviderConfigurationEntity updatedConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(configuration.LibraryId, configuration.PluginId, 5); updatedConfiguration.IsEnabled = true; // Act @@ -140,8 +140,8 @@ public class ArtworkProviderConfigurationRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); - LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -160,8 +160,8 @@ public class ArtworkProviderConfigurationRepositoryTests { // Arrange Guid pluginId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity configurationOfPlugin = _configurationFixture.Create(Guid.NewGuid(), pluginId, 1); - LibraryArtworkProviderConfigurationEntity configurationOfAnotherPlugin = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configurationOfPlugin = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), pluginId, 1); + LibraryArtworkProviderConfigurationEntity configurationOfAnotherPlugin = _libraryArtworkProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin); await _mockContext.SaveChangesAsync(); @@ -182,8 +182,8 @@ public class ArtworkProviderConfigurationRepositoryTests Guid libraryId = Guid.NewGuid(); Guid removedPluginId = Guid.NewGuid(); Guid keptPluginId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity removedConfiguration = _configurationFixture.Create(libraryId, removedPluginId, 1); - LibraryArtworkProviderConfigurationEntity keptConfiguration = _configurationFixture.Create(libraryId, keptPluginId, 2); + LibraryArtworkProviderConfigurationEntity removedConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, removedPluginId, 1); + LibraryArtworkProviderConfigurationEntity keptConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, keptPluginId, 2); _mockContext.LibraryArtworkProviderConfigurations.AddRange(removedConfiguration, keptConfiguration); await _mockContext.SaveChangesAsync(); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryBookReaderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryBookReaderConfigurationRepositoryTests.cs index 0b1db100..9b5bfba4 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryBookReaderConfigurationRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryBookReaderConfigurationRepositoryTests.cs @@ -23,7 +23,7 @@ public class LibraryBookReaderConfigurationRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly LibraryBookReaderConfigurationRepository _sut; - private readonly LibraryBookReaderConfigurationEntityFixture _configurationFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -39,8 +39,8 @@ public class LibraryBookReaderConfigurationRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryBookReaderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId: libraryId); - LibraryBookReaderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(); + LibraryBookReaderConfigurationEntity configurationOfLibrary = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId); + LibraryBookReaderConfigurationEntity configurationOfAnotherLibrary = _libraryBookReaderConfigurationEntityFixture.Create(); _mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -57,7 +57,7 @@ public class LibraryBookReaderConfigurationRepositoryTests public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt() { // Arrange - LibraryBookReaderConfigurationEntity configuration = _configurationFixture.Create(); + LibraryBookReaderConfigurationEntity configuration = _libraryBookReaderConfigurationEntityFixture.Create(); _mockContext.LibraryBookReaderConfigurations.Add(configuration); await _mockContext.SaveChangesAsync(); @@ -84,7 +84,7 @@ public class LibraryBookReaderConfigurationRepositoryTests public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt() { // Arrange - LibraryBookReaderConfigurationEntity configuration = _configurationFixture.Create(); + LibraryBookReaderConfigurationEntity configuration = _libraryBookReaderConfigurationEntityFixture.Create(); // Act Result result = await _sut.UpsertAsync(configuration, CancellationToken.None); @@ -99,11 +99,11 @@ public class LibraryBookReaderConfigurationRepositoryTests public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt() { // Arrange - LibraryBookReaderConfigurationEntity configuration = _configurationFixture.Create(isEnabled: false); + LibraryBookReaderConfigurationEntity configuration = _libraryBookReaderConfigurationEntityFixture.Create(isEnabled: false); _mockContext.LibraryBookReaderConfigurations.Add(configuration); await _mockContext.SaveChangesAsync(); - LibraryBookReaderConfigurationEntity updatedConfiguration = _configurationFixture.Create(libraryId: configuration.LibraryId, pluginId: configuration.PluginId, isEnabled: true); + LibraryBookReaderConfigurationEntity updatedConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: configuration.LibraryId, pluginId: configuration.PluginId, isEnabled: true); // Act Result result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None); @@ -121,8 +121,8 @@ public class LibraryBookReaderConfigurationRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryBookReaderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId: libraryId); - LibraryBookReaderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(); + LibraryBookReaderConfigurationEntity configurationOfLibrary = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId); + LibraryBookReaderConfigurationEntity configurationOfAnotherLibrary = _libraryBookReaderConfigurationEntityFixture.Create(); _mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -141,8 +141,8 @@ public class LibraryBookReaderConfigurationRepositoryTests { // Arrange Guid pluginId = Guid.NewGuid(); - LibraryBookReaderConfigurationEntity configurationOfPlugin = _configurationFixture.Create(pluginId: pluginId); - LibraryBookReaderConfigurationEntity configurationOfAnotherPlugin = _configurationFixture.Create(); + LibraryBookReaderConfigurationEntity configurationOfPlugin = _libraryBookReaderConfigurationEntityFixture.Create(pluginId: pluginId); + LibraryBookReaderConfigurationEntity configurationOfAnotherPlugin = _libraryBookReaderConfigurationEntityFixture.Create(); _mockContext.LibraryBookReaderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin); await _mockContext.SaveChangesAsync(); @@ -163,8 +163,8 @@ public class LibraryBookReaderConfigurationRepositoryTests Guid libraryId = Guid.NewGuid(); Guid removedPluginId = Guid.NewGuid(); Guid keptPluginId = Guid.NewGuid(); - LibraryBookReaderConfigurationEntity removedConfiguration = _configurationFixture.Create(libraryId: libraryId, pluginId: removedPluginId); - LibraryBookReaderConfigurationEntity keptConfiguration = _configurationFixture.Create(libraryId: libraryId, pluginId: keptPluginId); + LibraryBookReaderConfigurationEntity removedConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: removedPluginId); + LibraryBookReaderConfigurationEntity keptConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: keptPluginId); _mockContext.LibraryBookReaderConfigurations.AddRange(removedConfiguration, keptConfiguration); await _mockContext.SaveChangesAsync(); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs index be0b5039..33d9c60d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs @@ -22,7 +22,7 @@ public class LibraryMetadataProviderConfigurationRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly LibraryMetadataProviderConfigurationRepository _sut; - private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -38,8 +38,8 @@ public class LibraryMetadataProviderConfigurationRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); - LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -56,7 +56,7 @@ public class LibraryMetadataProviderConfigurationRepositoryTests public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt() { // Arrange - LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configuration = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryMetadataProviderConfigurations.Add(configuration); await _mockContext.SaveChangesAsync(); @@ -72,7 +72,7 @@ public class LibraryMetadataProviderConfigurationRepositoryTests public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt() { // Arrange - LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configuration = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); // Act Result result = await _sut.UpsertAsync(configuration, CancellationToken.None); @@ -87,11 +87,11 @@ public class LibraryMetadataProviderConfigurationRepositoryTests public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt() { // Arrange - LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configuration = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryMetadataProviderConfigurations.Add(configuration); await _mockContext.SaveChangesAsync(); - LibraryMetadataProviderConfigurationEntity updatedConfiguration = _configurationFixture.Create(configuration.LibraryId, configuration.PluginId, 5); + LibraryMetadataProviderConfigurationEntity updatedConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(configuration.LibraryId, configuration.PluginId, 5); updatedConfiguration.IsEnabled = true; // Act @@ -110,8 +110,8 @@ public class LibraryMetadataProviderConfigurationRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); - LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -130,8 +130,8 @@ public class LibraryMetadataProviderConfigurationRepositoryTests { // Arrange Guid pluginId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity configurationOfPlugin = _configurationFixture.Create(Guid.NewGuid(), pluginId, 1); - LibraryMetadataProviderConfigurationEntity configurationOfAnotherPlugin = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configurationOfPlugin = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), pluginId, 1); + LibraryMetadataProviderConfigurationEntity configurationOfAnotherPlugin = _libraryMetadataProviderConfigurationEntityFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin); await _mockContext.SaveChangesAsync(); @@ -152,8 +152,8 @@ public class LibraryMetadataProviderConfigurationRepositoryTests Guid libraryId = Guid.NewGuid(); Guid removedPluginId = Guid.NewGuid(); Guid keptPluginId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity removedConfiguration = _configurationFixture.Create(libraryId, removedPluginId, 1); - LibraryMetadataProviderConfigurationEntity keptConfiguration = _configurationFixture.Create(libraryId, keptPluginId, 2); + LibraryMetadataProviderConfigurationEntity removedConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, removedPluginId, 1); + LibraryMetadataProviderConfigurationEntity keptConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, keptPluginId, 2); _mockContext.LibraryMetadataProviderConfigurations.AddRange(removedConfiguration, keptConfiguration); await _mockContext.SaveChangesAsync(); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs index 41d5cf96..b27b5a3f 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs @@ -28,7 +28,7 @@ public class PluginRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly PluginRepository _sut; - private readonly PluginEntityFixture _pluginFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +43,7 @@ public class PluginRepositoryTests public async Task GetByIdAsync_WhenPluginExists_ShouldReturnIt() { // Arrange - PluginEntity plugin = _pluginFixture.Create(); + PluginEntity plugin = _pluginEntityFixture.Create(); _mockContext.Plugins.Add(plugin); await _mockContext.SaveChangesAsync(); @@ -59,7 +59,7 @@ public class PluginRepositoryTests public async Task UpsertAsync_WhenPluginDoesNotExist_ShouldInsertIt() { // Arrange - PluginEntity plugin = _pluginFixture.Create(); + PluginEntity plugin = _pluginEntityFixture.Create(); // Act Result result = await _sut.UpsertAsync(plugin, CancellationToken.None); @@ -74,12 +74,12 @@ public class PluginRepositoryTests public async Task UpsertAsync_WhenPluginExists_ShouldUpdateDetectionFieldsAndPreserveSettings() { // Arrange - PluginEntity plugin = _pluginFixture.Create(); + PluginEntity plugin = _pluginEntityFixture.Create(); plugin.SettingsJson = """{"preferredLanguage":"en"}"""; _mockContext.Plugins.Add(plugin); await _mockContext.SaveChangesAsync(); - PluginEntity updatedPlugin = _pluginFixture.Create(plugin.Id); + PluginEntity updatedPlugin = _pluginEntityFixture.Create(plugin.Id); updatedPlugin.Name = "Updated Name"; updatedPlugin.SettingsJson = null; // The stored settings must be preserved. @@ -98,7 +98,7 @@ public class PluginRepositoryTests public async Task UpdateSettingsAsync_WhenPluginExists_ShouldUpdateItsSettings() { // Arrange - PluginEntity plugin = _pluginFixture.Create(); + PluginEntity plugin = _pluginEntityFixture.Create(); _mockContext.Plugins.Add(plugin); await _mockContext.SaveChangesAsync(); @@ -126,7 +126,7 @@ public class PluginRepositoryTests public async Task GetAllAsync_WhenPluginsExist_ShouldReturnAllPlugins() { // Arrange - List plugins = _pluginFixture.CreateMany(2); + List plugins = _pluginEntityFixture.CreateMany(2); _mockContext.Plugins.AddRange(plugins); await _mockContext.SaveChangesAsync(); @@ -158,7 +158,7 @@ public class PluginRepositoryTests public async Task DeleteByIdAsync_WhenPluginExists_ShouldRemovePluginAndReturnDeleted() { // Arrange - PluginEntity existingPlugin = _pluginFixture.Create(); + PluginEntity existingPlugin = _pluginEntityFixture.Create(); _mockContext.Plugins.Add(existingPlugin); await _mockContext.SaveChangesAsync(); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index 67b3fa86..93e95a95 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -569,7 +569,7 @@ public class DataSeedServiceTests } [Fact] - public async Task SetDefaultScheduledJobsAsync_WhenCalled_ShouldInsertTheFiveDefaultJobsAndReturnCreated() + public async Task SetDefaultScheduledJobsAsync_WhenCalled_ShouldInsertTheSixDefaultJobsAndReturnCreated() { // Arrange Guid adminUserId = Guid.NewGuid(); @@ -586,7 +586,7 @@ public class DataSeedServiceTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); - Assert.Equal(5, capturedScheduledJobs.Count); + Assert.Equal(6, capturedScheduledJobs.Count); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status)); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.OwnerUserId)); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.CreatedBy)); @@ -596,8 +596,9 @@ public class DataSeedServiceTests Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes && scheduledJob.IntervalMinutes == 720); Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.RepairThemes && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanScheduledJobExecutionHistory && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); - await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any(), Arg.Any()); + await mockScheduledJobRepository.Received(6).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); await mockScheduledJobRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index 3def4bad..2109881b 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Common.DependencyInjection; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Common.Setup; @@ -29,6 +30,7 @@ namespace Lumina.DataAccess.UnitTests.Core.UoW; public class UnitOfWorkTests { private readonly IFixture _fixture; + private readonly RoleEntityFixture _roleEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -117,7 +119,7 @@ public class UnitOfWorkTests .Options; LuminaDbContext dbContext = new(options); UnitOfWork unitOfWork = new(dbContext); - dbContext.Roles.Add(new RoleEntity { Id = Guid.NewGuid(), RoleName = "TestRole" }); + dbContext.Roles.Add(_roleEntityFixture.Create(id: Guid.NewGuid(), roleName: "TestRole")); await dbContext.SaveChangesAsync(CancellationToken.None); Assert.NotEmpty(dbContext.ChangeTracker.Entries()); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj index 412dce36..47f88e4c 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/ArtworkStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/ArtworkStatusTests.cs new file mode 100644 index 00000000..0592e1e8 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/ArtworkStatusTests.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class ArtworkStatusTests +{ + [Fact] + public void ArtworkStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + ArtworkStatus[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MetadataStatusTests.cs similarity index 83% rename from tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs rename to tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MetadataStatusTests.cs index 5c52d627..9b536e97 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MetadataStatusTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; /// /// Contains unit tests for the enumeration. diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Lumina.Domain.SharedKernel.UnitTests.csproj b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Lumina.Domain.SharedKernel.UnitTests.csproj index 1955d88b..f6dd1c51 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Lumina.Domain.SharedKernel.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Lumina.Domain.SharedKernel.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 4f2edd5c..7cd1e9a8 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -42,7 +42,7 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(14, typeof(DomainErrors.Library).GetProperties().Length); + Assert.Equal(18, typeof(DomainErrors.Library).GetProperties().Length); AssertError(DomainErrors.Library.CannotScanLockedLibrary, ErrorType.Forbidden); AssertError(DomainErrors.Library.CannotScanDisabledLibrary, ErrorType.Forbidden); AssertError(DomainErrors.Library.LibraryIdCannotBeEmpty, ErrorType.Validation); @@ -52,11 +52,15 @@ public class ErrorsTests AssertError(DomainErrors.Library.LibraryNotFound, ErrorType.NotFound); AssertError(DomainErrors.Library.LibraryTypeCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Library.CoverFileMustBeAnImage, ErrorType.Validation); - AssertError(DomainErrors.Library.UnknownLibraryType, ErrorType.Unexpected); + AssertError(DomainErrors.Library.UnknownLibraryType, ErrorType.Forbidden); AssertError(DomainErrors.Library.PathsListCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Library.PathsListCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Library.TitleCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Library.TitleMustBeMaximum255CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, ErrorType.Validation); + AssertError(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, ErrorType.Validation); + AssertError(DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType, ErrorType.Validation); } [Fact] @@ -164,7 +168,7 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(12, typeof(DomainErrors.MediaContributor).GetProperties().Length); + Assert.Equal(13, typeof(DomainErrors.MediaContributor).GetProperties().Length); AssertError(DomainErrors.MediaContributor.ContributorNameCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorDisplayNameCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong, ErrorType.Validation); @@ -176,6 +180,7 @@ public class ErrorsTests AssertError(DomainErrors.MediaContributor.ContributorsListCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.MediaContributorIdCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.MediaContributorNotFound, ErrorType.NotFound); + AssertError(DomainErrors.MediaContributor.MediaContributorAlreadyExists, ErrorType.Conflict); AssertError(DomainErrors.MediaContributor.UnknownMediaContributorRole, ErrorType.Validation); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataTests.cs index 9dc21ced..94947845 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioMetadataTests.cs @@ -41,7 +41,12 @@ public class AudioMetadataTests Optional.None(), Optional.Some(16), Optional.Some("PCM"), - Optional.Some(1411)); + Optional.Some(1411), + Optional.Some("f0e9c1a2-0000-0000-0000-000000000000"), + Optional.Some(-6.53m), + Optional.Some(0.988m), + Optional.Some(-7.01m), + Optional.Some(1.001m)); // Assert Assert.False(result.IsFailure); @@ -75,7 +80,12 @@ public class AudioMetadataTests Optional.None(), Optional.None(), Optional.None(), - Optional.None()); + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); // Assert Assert.False(result.IsFailure); @@ -190,7 +200,12 @@ public class AudioMetadataTests Optional.Some(originalLanguage), Optional.Some(16), Optional.Some("PCM"), - Optional.Some(1411)); + Optional.Some(1411), + Optional.Some("f0e9c1a2-0000-0000-0000-000000000000"), + Optional.Some(-6.53m), + Optional.Some(0.988m), + Optional.Some(-7.01m), + Optional.Some(1.001m)); // Assert Assert.False(result.IsFailure); @@ -222,7 +237,12 @@ public class AudioMetadataTests Optional.None(), Optional.None(), Optional.None(), - Optional.None()); + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); // Assert Assert.False(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs index 82eefad2..bb4608fd 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs @@ -41,6 +41,7 @@ public class ArtistTests private readonly AudioMetadataFixture _audioMetadataFixture = new(); private readonly MoodFixture _moodFixture = new(); private readonly IsrcFixture _isrcFixture = new(); + private readonly MusicWorkFixture _musicWorkFixture = new(); [Fact] public void AddTrackToAlbum_WhenAlbumIsOwnedByTheArtist_ShouldAddTheTrackAndReturnSuccess() @@ -109,8 +110,25 @@ public class ArtistTests Result result = Artist.Create( libraryId, "Queen", + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, Optional.Some("https://www.queenonline.com"), Optional.Some(musicBrainzArtistId), + [], + [], + [], + [], + [], + [], contributors, [album]); @@ -141,8 +159,25 @@ public class ArtistTests libraryId, "Queen", Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, + Optional.None(), Optional.None(), [], + [], + [], + [], + [], + [], + [], [album]); // Assert @@ -165,8 +200,25 @@ public class ArtistTests _libraryIdFixture.Create(), name!, Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, + Optional.None(), Optional.None(), [], + [], + [], + [], + [], + [], + [], [_albumFixture.Create()]); // Assert @@ -182,8 +234,25 @@ public class ArtistTests _libraryIdFixture.Create(), "Queen", Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, + Optional.None(), Optional.None(), [], + [], + [], + [], + [], + [], + [], []); // Assert @@ -206,9 +275,26 @@ public class ArtistTests artistId, libraryId, "Queen", + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, Optional.Some("https://www.queenonline.com"), Optional.None(), [], + [], + [], + [], + [], + [], + [], [album], createdOnUtc, Optional.Some(updatedOnUtc)); @@ -236,8 +322,25 @@ public class ArtistTests _libraryIdFixture.Create(), name!, Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, + Optional.None(), Optional.None(), [], + [], + [], + [], + [], + [], + [], [_albumFixture.Create()], DateTime.UtcNow, Optional.None()); @@ -256,9 +359,26 @@ public class ArtistTests _libraryIdFixture.Create(), "Queen", Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, + Optional.None(), Optional.None(), [], [], + [], + [], + [], + [], + [], + [], DateTime.UtcNow, Optional.None()); @@ -394,6 +514,17 @@ public class ArtistTests // Act Result result = artist.UpdateDetails( "Queen", + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, Optional.Some("https://www.queenonline.com"), Optional.Some(musicBrainzArtistId)); @@ -415,7 +546,21 @@ public class ArtistTests Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; // Act - Result result = artist.UpdateDetails(" ", Optional.None(), Optional.None()); + Result result = artist.UpdateDetails( + " ", + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + false, + Optional.None(), + Optional.None()); // Assert Assert.True(result.IsFailure); @@ -433,7 +578,7 @@ public class ArtistTests AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Night at the Opera"); Optional mediaFormat = Optional.Some(MusicMediaFormat.CD); Optional barcode = Optional.Some(_barcodeFixture.Create()); - Optional catalogNumber = Optional.Some("CAT-123456"); + List catalogNumbers = ["CAT-123456"]; Optional releaseId = Optional.Some(_musicBrainzIdFixture.Create()); Optional releaseGroupId = Optional.Some(_musicBrainzIdFixture.Create()); Optional releaseArtistId = Optional.Some(_musicBrainzIdFixture.Create()); @@ -445,9 +590,14 @@ public class ArtistTests Result result = artist.UpdateAlbum( album, metadata, + Optional.None(), mediaFormat, + Optional.None(), + Optional.None(), barcode, - catalogNumber, + catalogNumbers, + Optional.None(), + Optional.None(), releaseId, releaseGroupId, releaseArtistId, @@ -459,7 +609,7 @@ public class ArtistTests Assert.Equal(metadata, album.Metadata); Assert.Equal(mediaFormat, album.MediaFormat); Assert.Equal(barcode, album.Barcode); - Assert.Equal(catalogNumber, album.CatalogNumber); + Assert.Equal(catalogNumbers, album.CatalogNumbers); Assert.Equal(releaseId, album.MusicBrainzReleaseId); Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId); Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId); @@ -483,8 +633,13 @@ public class ArtistTests Result result = artist.UpdateAlbum( foreignAlbum, _albumMetadataFixture.Create(), + Optional.None(), Optional.None(), + Optional.None(), + Optional.None(), Optional.None(), + [], + Optional.None(), Optional.None(), Optional.None(), Optional.None(), @@ -512,10 +667,9 @@ public class ArtistTests Optional script = Optional.Some("Latin"); Optional key = Optional.Some(MusicKey.BMajor); Optional bpm = Optional.Some(72); - Optional work = Optional.Some("Bohemian Rhapsody"); + Optional work = Optional.Some(_musicWorkFixture.Create(title: "Bohemian Rhapsody")); Optional recordingId = Optional.Some(_musicBrainzIdFixture.Create()); Optional musicBrainzTrackId = Optional.Some(_musicBrainzIdFixture.Create()); - Optional workId = Optional.Some(_musicBrainzIdFixture.Create()); List moods = [_moodFixture.Create(name: "epic")]; List isrcs = [_isrcFixture.Create(value: "GBUM71029604")]; List contributors = [_musicMediaContributorFixture.Create()]; @@ -533,10 +687,10 @@ public class ArtistTests script, key, bpm, + true, work, recordingId, musicBrainzTrackId, - workId, moods, isrcs, contributors, @@ -551,10 +705,10 @@ public class ArtistTests Assert.Equal(script, track.Script); Assert.Equal(key, track.Key); Assert.Equal(bpm, track.Bpm); + Assert.True(track.IsVideo); Assert.Equal(work, track.Work); Assert.Equal(recordingId, track.MusicBrainzRecordingId); Assert.Equal(musicBrainzTrackId, track.MusicBrainzTrackId); - Assert.Equal(workId, track.MusicBrainzWorkId); Assert.Equal(moods, track.Moods); Assert.Equal(isrcs, track.Isrcs); Assert.Equal(contributors, track.Contributors); @@ -585,8 +739,8 @@ public class ArtistTests Optional.None(), Optional.None(), Optional.None(), - Optional.None(), - Optional.None(), + false, + Optional.None(), Optional.None(), Optional.None(), [], @@ -622,8 +776,8 @@ public class ArtistTests Optional.None(), Optional.None(), Optional.None(), - Optional.None(), - Optional.None(), + false, + Optional.None(), Optional.None(), Optional.None(), [], diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumTests.cs index 0c563880..8f27b8dc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumTests.cs @@ -71,7 +71,7 @@ public class AlbumTests AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Night at the Opera"); Optional mediaFormat = Optional.Some(MusicMediaFormat.Vinyl); Optional barcode = Optional.Some(_barcodeFixture.Create()); - Optional catalogNumber = Optional.Some("CAT-001"); + List catalogNumbers = ["CAT-001"]; Optional releaseId = Optional.Some(_musicBrainzIdFixture.Create()); Optional releaseGroupId = Optional.Some(_musicBrainzIdFixture.Create()); Optional releaseArtistId = Optional.Some(_musicBrainzIdFixture.Create()); @@ -83,9 +83,14 @@ public class AlbumTests // Act Result result = Album.Create( metadata, + Optional.None(), mediaFormat, + Optional.Some(MusicReleasePackaging.Digipak), + Optional.None(), barcode, - catalogNumber, + catalogNumbers, + Optional.Some("Label"), + Optional.Some("ASIN"), releaseId, releaseGroupId, releaseArtistId, @@ -100,7 +105,7 @@ public class AlbumTests Assert.Equal(metadata, album.Metadata); Assert.Equal(mediaFormat, album.MediaFormat); Assert.Equal(barcode, album.Barcode); - Assert.Equal(catalogNumber, album.CatalogNumber); + Assert.Equal(catalogNumbers, album.CatalogNumbers); Assert.Equal(releaseId, album.MusicBrainzReleaseId); Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId); Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId); @@ -117,8 +122,13 @@ public class AlbumTests // Act Result result = Album.Create( _albumMetadataFixture.Create(), + Optional.None(), Optional.None(), + Optional.None(), + Optional.None(), Optional.None(), + [], + Optional.None(), Optional.None(), Optional.None(), Optional.None(), @@ -132,7 +142,7 @@ public class AlbumTests Album album = result.Value; Assert.False(album.MediaFormat.HasValue); Assert.False(album.Barcode.HasValue); - Assert.False(album.CatalogNumber.HasValue); + Assert.Empty(album.CatalogNumbers); Assert.False(album.MusicBrainzReleaseId.HasValue); Assert.False(album.MusicBrainzReleaseGroupId.HasValue); Assert.False(album.MusicBrainzReleaseArtistId.HasValue); @@ -144,8 +154,13 @@ public class AlbumTests // Act Result result = Album.Create( _albumMetadataFixture.Create(), + Optional.None(), Optional.None(), + Optional.None(), + Optional.None(), Optional.None(), + [], + Optional.None(), Optional.None(), Optional.None(), Optional.None(), @@ -174,9 +189,14 @@ public class AlbumTests Result result = Album.Create( albumId, metadata, + Optional.None(), Optional.Some(MusicMediaFormat.CD), + Optional.None(), + Optional.None(), Optional.Some(_barcodeFixture.Create()), - Optional.Some("CAT-002"), + ["CAT-002"], + Optional.None(), + Optional.None(), Optional.None(), Optional.None(), Optional.None(), @@ -299,7 +319,7 @@ public class AlbumTests AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Day at the Races"); Optional mediaFormat = Optional.Some(MusicMediaFormat.Cassette); Optional barcode = Optional.Some(_barcodeFixture.Create()); - Optional catalogNumber = Optional.Some("CAT-003"); + List catalogNumbers = ["CAT-003"]; Optional releaseId = Optional.Some(_musicBrainzIdFixture.Create()); Optional releaseGroupId = Optional.Some(_musicBrainzIdFixture.Create()); Optional releaseArtistId = Optional.Some(_musicBrainzIdFixture.Create()); @@ -308,9 +328,14 @@ public class AlbumTests // Act Result result = album.UpdateDetails( metadata, + Optional.None(), mediaFormat, + Optional.None(), + Optional.None(), barcode, - catalogNumber, + catalogNumbers, + Optional.None(), + Optional.None(), releaseId, releaseGroupId, releaseArtistId); @@ -320,7 +345,7 @@ public class AlbumTests Assert.Equal(metadata, album.Metadata); Assert.Equal(mediaFormat, album.MediaFormat); Assert.Equal(barcode, album.Barcode); - Assert.Equal(catalogNumber, album.CatalogNumber); + Assert.Equal(catalogNumbers, album.CatalogNumbers); Assert.Equal(releaseId, album.MusicBrainzReleaseId); Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId); Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId); @@ -339,8 +364,13 @@ public class AlbumTests // Act Result result = album.UpdateDetails( _albumMetadataFixture.Create(), + Optional.None(), Optional.None(), + Optional.None(), + Optional.None(), Optional.None(), + [], + Optional.None(), Optional.None(), Optional.None(), Optional.None(), @@ -350,7 +380,7 @@ public class AlbumTests Assert.False(result.IsFailure); Assert.False(album.MediaFormat.HasValue); Assert.False(album.Barcode.HasValue); - Assert.False(album.CatalogNumber.HasValue); + Assert.Empty(album.CatalogNumbers); Assert.False(album.MusicBrainzReleaseId.HasValue); Assert.False(album.MusicBrainzReleaseGroupId.HasValue); Assert.False(album.MusicBrainzReleaseArtistId.HasValue); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs index 382cc58f..86fec38c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs @@ -30,6 +30,7 @@ public class TrackTests private readonly AudioRatingFixture _audioRatingFixture = new(); private readonly AudioMetadataFixture _audioMetadataFixture = new(); private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly MusicWorkFixture _musicWorkFixture = new(); [Fact] public void Create_WhenCalledWithValidData_ShouldCreateTrackWithAllPropertiesPopulated() @@ -54,9 +55,9 @@ public class TrackTests Assert.True(track.Bpm.HasValue); Assert.NotEmpty(track.Isrcs); Assert.True(track.Work.HasValue); + Assert.NotEqual(Guid.Empty, track.Work.Value.MusicBrainzWorkId.Value); Assert.True(track.MusicBrainzRecordingId.HasValue); Assert.True(track.MusicBrainzTrackId.HasValue); - Assert.True(track.MusicBrainzWorkId.HasValue); Assert.NotEmpty(track.Contributors); Assert.NotEmpty(track.Ratings); Assert.InRange(track.CreatedOnUtc, beforeCreate, DateTime.UtcNow); @@ -76,17 +77,18 @@ public class TrackTests sourceTrack.Id, sourceTrack.Path, sourceTrack.Metadata, + sourceTrack.Disambiguation, sourceTrack.TrackNumber, sourceTrack.DiscNumber, [.. sourceTrack.Moods], sourceTrack.Script, sourceTrack.Key, sourceTrack.Bpm, + sourceTrack.IsVideo, [.. sourceTrack.Isrcs], sourceTrack.Work, sourceTrack.MusicBrainzRecordingId, sourceTrack.MusicBrainzTrackId, - sourceTrack.MusicBrainzWorkId, [.. sourceTrack.Contributors], [.. sourceTrack.Ratings], createdOnUtc, @@ -195,10 +197,10 @@ public class TrackTests Optional script = Optional.Some("Latin"); Optional key = Optional.Some(MusicKey.DMajor); Optional bpm = Optional.Some(128); - Optional work = Optional.Some("Symphony No. 5"); + bool isVideo = true; + Optional work = Optional.Some(_musicWorkFixture.Create(title: "Symphony No. 5")); Optional recordingId = Optional.Some(_musicBrainzIdFixture.Create()); Optional trackId = Optional.Some(_musicBrainzIdFixture.Create()); - Optional workId = Optional.Some(_musicBrainzIdFixture.Create()); DateTime beforeUpdate = DateTime.UtcNow; // Act @@ -210,10 +212,10 @@ public class TrackTests script, key, bpm, + isVideo, work, recordingId, - trackId, - workId); + trackId); // Assert Assert.False(result.IsFailure); @@ -224,10 +226,10 @@ public class TrackTests Assert.Equal(script, track.Script); Assert.Equal(key, track.Key); Assert.Equal(bpm, track.Bpm); + Assert.True(track.IsVideo); Assert.Equal(work, track.Work); Assert.Equal(recordingId, track.MusicBrainzRecordingId); Assert.Equal(trackId, track.MusicBrainzTrackId); - Assert.Equal(workId, track.MusicBrainzWorkId); Assert.True(track.UpdatedOnUtc.HasValue); Assert.True(track.UpdatedOnUtc.Value >= beforeUpdate); // the collections are not part of the details update @@ -245,10 +247,9 @@ public class TrackTests key: Optional.None(), bpm: Optional.None(), isrcs: [], - work: Optional.None(), + work: Optional.None(), musicBrainzRecordingId: Optional.None(), musicBrainzTrackId: Optional.None(), - musicBrainzWorkId: Optional.None(), contributors: [], ratings: []); @@ -260,7 +261,6 @@ public class TrackTests Assert.False(track.Work.HasValue); Assert.False(track.MusicBrainzRecordingId.HasValue); Assert.False(track.MusicBrainzTrackId.HasValue); - Assert.False(track.MusicBrainzWorkId.HasValue); Assert.Empty(track.Moods); Assert.Empty(track.Isrcs); Assert.Empty(track.Contributors); @@ -280,17 +280,18 @@ public class TrackTests sourceTrack.Id, sourceTrack.Path, sourceTrack.Metadata, + sourceTrack.Disambiguation, sourceTrack.TrackNumber, sourceTrack.DiscNumber, [.. sourceTrack.Moods], sourceTrack.Script, sourceTrack.Key, sourceTrack.Bpm, + sourceTrack.IsVideo, [.. sourceTrack.Isrcs], sourceTrack.Work, sourceTrack.MusicBrainzRecordingId, sourceTrack.MusicBrainzTrackId, - sourceTrack.MusicBrainzWorkId, [.. sourceTrack.Contributors], [.. sourceTrack.Ratings], createdOnUtc, @@ -305,7 +306,6 @@ public class TrackTests Assert.Equal(sourceTrack.Work, track.Work); Assert.Equal(sourceTrack.MusicBrainzRecordingId, track.MusicBrainzRecordingId); Assert.Equal(sourceTrack.MusicBrainzTrackId, track.MusicBrainzTrackId); - Assert.Equal(sourceTrack.MusicBrainzWorkId, track.MusicBrainzWorkId); // The pre-existing identity and the provided timestamps must survive the rehydration. Assert.Equal(sourceTrack.Id, track.Id); Assert.Equal(createdOnUtc, track.CreatedOnUtc); @@ -380,8 +380,8 @@ public class TrackTests Optional.None(), Optional.None(), Optional.None(), - Optional.None(), - Optional.None(), + false, + Optional.None(), Optional.None(), Optional.None()); @@ -391,9 +391,9 @@ public class TrackTests Assert.False(track.Script.HasValue); Assert.False(track.Key.HasValue); Assert.False(track.Bpm.HasValue); + Assert.False(track.IsVideo); Assert.False(track.Work.HasValue); Assert.False(track.MusicBrainzRecordingId.HasValue); Assert.False(track.MusicBrainzTrackId.HasValue); - Assert.False(track.MusicBrainzWorkId.HasValue); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalogTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalogTests.cs new file mode 100644 index 00000000..13a273f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalogTests.cs @@ -0,0 +1,163 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryPathPartCatalogTests +{ + private readonly MusicLibraryPathPartCatalog _sut = new(); + + [Fact] + public void SupportedLibraryType_WhenCalled_ShouldReturnMusic() + { + // Act + LibraryType result = _sut.SupportedLibraryType; + + // Assert + Assert.Equal(LibraryType.Music, result); + } + + [Fact] + public void GetPartDefinitions_WhenCalled_ShouldReturnTheExpectedDefinitions() + { + // Act + IReadOnlyList result = _sut.GetPartDefinitions(); + + // Assert + Assert.Equal(10, result.Count); + + Assert.Equal(LibraryPathPartKind.Literal, result[0].Kind); + Assert.Equal(LibraryPathValueType.None, result[0].ValueType); + Assert.Equal(string.Empty, result[0].DefaultRepresentation); + Assert.False(result[0].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind); + Assert.Equal(LibraryPathValueType.None, result[1].ValueType); + Assert.Equal(string.Empty, result[1].DefaultRepresentation); + Assert.False(result[1].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.Artist, result[2].Kind); + Assert.Equal(LibraryPathValueType.Text, result[2].ValueType); + Assert.Equal("{0}", result[2].DefaultRepresentation); + Assert.False(result[2].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.ReleaseType, result[3].Kind); + Assert.Equal(LibraryPathValueType.Enum, result[3].ValueType); + Assert.Equal("{0}", result[3].DefaultRepresentation); + Assert.False(result[3].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.ReleaseYear, result[4].Kind); + Assert.Equal(LibraryPathValueType.Year, result[4].ValueType); + Assert.Equal("{0}", result[4].DefaultRepresentation); + Assert.False(result[4].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.ReleaseName, result[5].Kind); + Assert.Equal(LibraryPathValueType.Text, result[5].ValueType); + Assert.Equal("{0}", result[5].DefaultRepresentation); + Assert.False(result[5].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.TrackNumber, result[6].Kind); + Assert.Equal(LibraryPathValueType.Integer, result[6].ValueType); + Assert.Equal("{0:00}", result[6].DefaultRepresentation); + Assert.False(result[6].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.TrackName, result[7].Kind); + Assert.Equal(LibraryPathValueType.Text, result[7].ValueType); + Assert.Equal("{0}", result[7].DefaultRepresentation); + Assert.False(result[7].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.Extension, result[8].Kind); + Assert.Equal(LibraryPathValueType.Text, result[8].ValueType); + Assert.Equal("{0}", result[8].DefaultRepresentation); + Assert.False(result[8].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.DiscNumber, result[9].Kind); + Assert.Equal(LibraryPathValueType.Integer, result[9].ValueType); + Assert.Equal("{0:00}", result[9].DefaultRepresentation); + Assert.True(result[9].IsOptionalByDefault); + } + + [Fact] + public void GetDefaultTemplate_WhenCalled_ShouldReturnTheExpectedParts() + { + // Act + IReadOnlyList result = _sut.GetDefaultTemplate().Parts; + + // Assert + Assert.Equal(16, result.Count); + + Assert.Equal(LibraryPathPartKind.Artist, result[0].Kind); + Assert.Equal("{0}", result[0].Representation); + Assert.False(result[0].IsOptional); + + Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind); + Assert.Equal(string.Empty, result[1].Representation); + Assert.False(result[1].IsOptional); + + Assert.Equal(LibraryPathPartKind.ReleaseType, result[2].Kind); + Assert.Equal("{0}", result[2].Representation); + Assert.False(result[2].IsOptional); + + Assert.Equal(LibraryPathPartKind.Separator, result[3].Kind); + Assert.Equal(string.Empty, result[3].Representation); + Assert.False(result[3].IsOptional); + + Assert.Equal(LibraryPathPartKind.ReleaseYear, result[4].Kind); + Assert.Equal("{0}", result[4].Representation); + Assert.False(result[4].IsOptional); + + Assert.Equal(LibraryPathPartKind.Literal, result[5].Kind); + Assert.Equal(" - ", result[5].Representation); + Assert.False(result[5].IsOptional); + + Assert.Equal(LibraryPathPartKind.ReleaseName, result[6].Kind); + Assert.Equal("{0}", result[6].Representation); + Assert.False(result[6].IsOptional); + + Assert.Equal(LibraryPathPartKind.Separator, result[7].Kind); + Assert.Equal(string.Empty, result[7].Representation); + Assert.True(result[7].IsOptional); + + Assert.Equal(LibraryPathPartKind.Literal, result[8].Kind); + Assert.Equal("Disk ", result[8].Representation); + Assert.True(result[8].IsOptional); + + Assert.Equal(LibraryPathPartKind.DiscNumber, result[9].Kind); + Assert.Equal("{0:00}", result[9].Representation); + Assert.True(result[9].IsOptional); + + Assert.Equal(LibraryPathPartKind.Separator, result[10].Kind); + Assert.Equal(string.Empty, result[10].Representation); + Assert.False(result[10].IsOptional); + + Assert.Equal(LibraryPathPartKind.TrackNumber, result[11].Kind); + Assert.Equal("{0:00}", result[11].Representation); + Assert.False(result[11].IsOptional); + + Assert.Equal(LibraryPathPartKind.Literal, result[12].Kind); + Assert.Equal(" - ", result[12].Representation); + Assert.False(result[12].IsOptional); + + Assert.Equal(LibraryPathPartKind.TrackName, result[13].Kind); + Assert.Equal("{0}", result[13].Representation); + Assert.False(result[13].IsOptional); + + Assert.Equal(LibraryPathPartKind.Literal, result[14].Kind); + Assert.Equal(".", result[14].Representation); + Assert.False(result[14].IsOptional); + + Assert.Equal(LibraryPathPartKind.Extension, result[15].Kind); + Assert.Equal("{0}", result[15].Representation); + Assert.False(result[15].IsOptional); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs new file mode 100644 index 00000000..2ad9ebb3 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryTypeScannerTests +{ + private readonly IMediaLibraryScanJobFactory _mockJobFactory = Substitute.For(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + [Fact] + public void SupportedLibraryType_ShouldBeMusic() + { + // Arrange + MusicLibraryTypeScanner sut = new(_mockJobFactory); + + // Act & Assert + Assert.Equal(LibraryType.Music, sut.SupportedLibraryType); + } + + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithEnrichmentJobs() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + TestScanJob discoveryJob = CreateJob(); + TestScanJob diffJob = CreateJob(); + TestScanJob hashJob = CreateJob(); + TestScanJob metadataExtractionJob = CreateJob(); + TestScanJob saveJob = CreateJob(); + TestScanJob invalidationJob = CreateJob(); + TestScanJob enrichmentJob = CreateJob(); + TestScanJob artworkEnrichmentJob = CreateJob(); + MusicLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + List rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)]; + + // Assert + IMediaLibraryScanJob rootJob = Assert.Single(rootJobs); + Assert.Same(discoveryJob, rootJob); + Assert.Contains(diffJob, discoveryJob.Children); + Assert.Contains(discoveryJob, diffJob.Parents); + Assert.Contains(hashJob, diffJob.Children); + Assert.Contains(diffJob, hashJob.Parents); + Assert.Contains(metadataExtractionJob, hashJob.Children); + Assert.Contains(hashJob, metadataExtractionJob.Parents); + Assert.Contains(saveJob, metadataExtractionJob.Children); + Assert.Contains(metadataExtractionJob, saveJob.Parents); + Assert.Contains(invalidationJob, saveJob.Children); + Assert.Contains(saveJob, invalidationJob.Parents); + Assert.Contains(enrichmentJob, invalidationJob.Children); + Assert.Contains(invalidationJob, enrichmentJob.Parents); + Assert.Contains(artworkEnrichmentJob, enrichmentJob.Children); + Assert.Contains(enrichmentJob, artworkEnrichmentJob.Parents); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + } + + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + MusicLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + _ = sut.CreateScanJobsForLibrary(libraryId).ToList(); + + // Assert + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + } + + private TestScanJob CreateJob() where TJob : class, IMediaLibraryScanJob + { + TestScanJob job = new() + { + ScanId = _scanIdFixture.Create(), + UserId = _userIdFixture.Create(), + LibraryId = _libraryIdFixture.Create() + }; + _mockJobFactory.CreateJob(Arg.Any()).Returns((TJob)(object)job); + return job; + } + + /// + /// Concrete test implementation of the abstract class that satisfies all job interfaces. + /// + private sealed class TestScanJob : MediaLibraryScanJob, + IMusicFileSystemDiscoveryJob, + IMediaLibraryScanDiffJob, + IMediaLibraryScanHashJob, + IMusicMetadataExtractionJob, + IMediaLibraryScanResultsSaveJob, + IMediaLibraryScanProviderConfigurationInvalidationJob, + IMediaLibraryScanMetadataEnrichmentJob, + IMediaLibraryScanArtworkEnrichmentJob + { + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter. + /// The unique identifier of the media library scan job. + /// The input data to be processed. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public override Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataTests.cs index a66b8e58..0eb101cf 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataTests.cs @@ -37,13 +37,14 @@ public class AlbumMetadataTests Result result = AlbumMetadata.Create( "A Night at the Opera", Optional.Some("A Night at the Opera (original)"), + Optional.Some("A Night at the Opera (2011 remaster)"), Optional.Some("The fourth studio album by the British rock band Queen."), releaseInfo, [genre], [tag], Optional.Some(language), Optional.Some(originalLanguage), - Optional.Some(MusicReleaseType.Album), + [MusicReleaseType.Album], Optional.Some(MusicReleaseStatus.Official), Optional.Some(2), 12); @@ -53,13 +54,14 @@ public class AlbumMetadataTests AlbumMetadata metadata = result.Value; Assert.Equal("A Night at the Opera", metadata.Title); Assert.Equal(Optional.Some("A Night at the Opera (original)"), metadata.OriginalTitle); + Assert.Equal(Optional.Some("A Night at the Opera (2011 remaster)"), metadata.ReleaseTitle); Assert.Equal(Optional.Some("The fourth studio album by the British rock band Queen."), metadata.Description); Assert.Equal(releaseInfo, metadata.ReleaseInfo); Assert.Equal(genre, Assert.Single(metadata.Genres)); Assert.Equal(tag, Assert.Single(metadata.Tags)); Assert.Equal(Optional.Some(language), metadata.Language); Assert.Equal(Optional.Some(originalLanguage), metadata.OriginalLanguage); - Assert.Equal(Optional.Some(MusicReleaseType.Album), metadata.ReleaseType); + Assert.Equal(new[] { MusicReleaseType.Album }, metadata.ReleaseTypes); Assert.Equal(Optional.Some(MusicReleaseStatus.Official), metadata.ReleaseStatus); Assert.Equal(Optional.Some(2), metadata.TotalDiscs); Assert.Equal(12, metadata.TotalTracks); @@ -73,12 +75,13 @@ public class AlbumMetadataTests "A Night at the Opera", Optional.None(), Optional.None(), + Optional.None(), _releaseInfoFixture.Create(), [], [], Optional.None(), Optional.None(), - Optional.None(), + [], Optional.None(), Optional.None(), 12); @@ -87,10 +90,11 @@ public class AlbumMetadataTests Assert.False(result.IsFailure); AlbumMetadata metadata = result.Value; Assert.False(metadata.OriginalTitle.HasValue); + Assert.False(metadata.ReleaseTitle.HasValue); Assert.False(metadata.Description.HasValue); Assert.False(metadata.Language.HasValue); Assert.False(metadata.OriginalLanguage.HasValue); - Assert.False(metadata.ReleaseType.HasValue); + Assert.Empty(metadata.ReleaseTypes); Assert.False(metadata.ReleaseStatus.HasValue); Assert.False(metadata.TotalDiscs.HasValue); Assert.Empty(metadata.Genres); @@ -113,12 +117,13 @@ public class AlbumMetadataTests "A Night at the Opera", Optional.None(), Optional.None(), + Optional.None(), _releaseInfoFixture.Create(), expectedGenres, expectedTags, Optional.None(), Optional.None(), - Optional.None(), + [], Optional.None(), Optional.None(), 12); @@ -139,26 +144,28 @@ public class AlbumMetadataTests AlbumMetadata firstMetadata = _albumMetadataFixture.Create( title: "A Night at the Opera", originalTitle: Optional.None(), + releaseTitle: Optional.Some("A Night at the Opera (2011 remaster)"), description: Optional.None(), releaseInfo: releaseInfo, genres: [_genreFixture.Create(name: "Rock")], tags: [_tagFixture.Create(name: "classic")], language: Optional.None(), originalLanguage: Optional.None(), - releaseType: Optional.Some(MusicReleaseType.Album), + releaseTypes: [MusicReleaseType.Album], releaseStatus: Optional.Some(MusicReleaseStatus.Official), totalDiscs: Optional.Some(2), totalTracks: 12); AlbumMetadata secondMetadata = _albumMetadataFixture.Create( title: "A Night at the Opera", originalTitle: Optional.None(), + releaseTitle: Optional.Some("A Night at the Opera (2011 remaster)"), description: Optional.None(), releaseInfo: releaseInfo, genres: [_genreFixture.Create(name: "Rock")], tags: [_tagFixture.Create(name: "classic")], language: Optional.None(), originalLanguage: Optional.None(), - releaseType: Optional.Some(MusicReleaseType.Album), + releaseTypes: [MusicReleaseType.Album], releaseStatus: Optional.Some(MusicReleaseStatus.Official), totalDiscs: Optional.Some(2), totalTracks: 12); @@ -191,11 +198,11 @@ public class AlbumMetadataTests AlbumMetadata firstMetadata = _albumMetadataFixture.Create( title: "A Night at the Opera", releaseInfo: releaseInfo, - releaseType: Optional.Some(MusicReleaseType.Album)); + releaseTypes: [MusicReleaseType.Album]); AlbumMetadata secondMetadata = _albumMetadataFixture.Create( title: "A Night at the Opera", releaseInfo: releaseInfo, - releaseType: Optional.Some(MusicReleaseType.Single)); + releaseTypes: [MusicReleaseType.Single]); // Assert Assert.NotEqual(firstMetadata, secondMetadata); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicAreaTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicAreaTests.cs new file mode 100644 index 00000000..1dadf494 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicAreaTests.cs @@ -0,0 +1,199 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicAreaTests +{ + private readonly MusicAreaFixture _musicAreaFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateMusicAreaWithAllPropertiesSet() + { + // Arrange + MusicBrainzId areaId = _musicBrainzIdFixture.Create(value: Guid.Parse("f0e9c1a2-0000-0000-0000-000000000000")); + + // Act + Result result = MusicArea.Create( + areaId, + "United Kingdom", + Optional.Some("UK"), + Optional.Some("The United Kingdom of Great Britain and Northern Ireland"), + Optional.Some("Country"), + Optional.Some("GB")); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(areaId, result.Value.MusicBrainzAreaId); + Assert.Equal("United Kingdom", result.Value.Name); + Assert.Equal(Optional.Some("UK"), result.Value.SortName); + Assert.Equal(Optional.Some("The United Kingdom of Great Britain and Northern Ireland"), result.Value.Disambiguation); + Assert.Equal(Optional.Some("Country"), result.Value.Type); + Assert.Equal(Optional.Some("GB"), result.Value.Iso3166Code); + } + + [Fact] + public void Create_WhenNameHasSurroundingWhitespace_ShouldTrimIt() + { + // Act + Result result = MusicArea.Create( + _musicBrainzIdFixture.Create(), + " United Kingdom ", + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("United Kingdom", result.Value.Name); + } + + [Theory] + [InlineData(null)] // null area name + [InlineData("")] // empty area name + [InlineData(" ")] // whitespace area name + public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + { + // Act + Result result = MusicArea.Create( + _musicBrainzIdFixture.Create(), + name!, + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AreaNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Create_WhenOptionalValuesAreAbsent_ShouldCreateMusicAreaWithoutThem() + { + // Act + Result result = MusicArea.Create( + _musicBrainzIdFixture.Create(), + "United Kingdom", + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.SortName.HasValue); + Assert.False(result.Value.Disambiguation.HasValue); + Assert.False(result.Value.Type.HasValue); + Assert.False(result.Value.Iso3166Code.HasValue); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + MusicArea firstArea = _musicAreaFixture.Create(); + + // Act + MusicArea secondArea = _musicAreaFixture.Create( + musicBrainzAreaId: firstArea.MusicBrainzAreaId, + name: firstArea.Name, + sortName: firstArea.SortName, + disambiguation: firstArea.Disambiguation, + type: firstArea.Type, + iso3166Code: firstArea.Iso3166Code); + + // Assert + Assert.Equal(firstArea, secondArea); + } + + [Fact] + public void Equals_WithDifferentMusicBrainzAreaId_ShouldReturnFalse() + { + // Arrange + MusicArea firstArea = _musicAreaFixture.Create(musicBrainzAreaId: _musicBrainzIdFixture.Create(value: Guid.Parse("11111111-1111-1111-1111-111111111111"))); + + // Act + MusicArea secondArea = _musicAreaFixture.Create(musicBrainzAreaId: _musicBrainzIdFixture.Create(value: Guid.Parse("22222222-2222-2222-2222-222222222222"))); + + // Assert + Assert.NotEqual(firstArea, secondArea); + } + + [Fact] + public void Equals_WithDifferentName_ShouldReturnFalse() + { + // Arrange + MusicArea firstArea = _musicAreaFixture.Create(name: "United Kingdom"); + + // Act + MusicArea secondArea = _musicAreaFixture.Create(name: "France"); + + // Assert + Assert.NotEqual(firstArea, secondArea); + } + + [Fact] + public void Equals_WithDifferentSortName_ShouldReturnFalse() + { + // Arrange + MusicArea firstArea = _musicAreaFixture.Create(sortName: Optional.Some("UK")); + + // Act + MusicArea secondArea = _musicAreaFixture.Create(sortName: Optional.Some("GB")); + + // Assert + Assert.NotEqual(firstArea, secondArea); + } + + [Fact] + public void Equals_WithDifferentDisambiguation_ShouldReturnFalse() + { + // Arrange + MusicArea firstArea = _musicAreaFixture.Create(disambiguation: Optional.Some("The country")); + + // Act + MusicArea secondArea = _musicAreaFixture.Create(disambiguation: Optional.Some("The region")); + + // Assert + Assert.NotEqual(firstArea, secondArea); + } + + [Fact] + public void Equals_WithDifferentType_ShouldReturnFalse() + { + // Arrange + MusicArea firstArea = _musicAreaFixture.Create(type: Optional.Some("Country")); + + // Act + MusicArea secondArea = _musicAreaFixture.Create(type: Optional.Some("City")); + + // Assert + Assert.NotEqual(firstArea, secondArea); + } + + [Fact] + public void Equals_WithDifferentIso3166Code_ShouldReturnFalse() + { + // Arrange + MusicArea firstArea = _musicAreaFixture.Create(iso3166Code: Optional.Some("GB")); + + // Act + MusicArea secondArea = _musicAreaFixture.Create(iso3166Code: Optional.Some("FR")); + + // Assert + Assert.NotEqual(firstArea, secondArea); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAliasTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAliasTests.cs new file mode 100644 index 00000000..9e84ec84 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicArtistAliasTests.cs @@ -0,0 +1,238 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtistAliasTests +{ + private readonly MusicArtistAliasFixture _musicArtistAliasFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateAliasWithAllPropertiesSet() + { + // Arrange + DateOnly beginDate = new(1970, 1, 1); + DateOnly endDate = new(1991, 1, 1); + + // Act + Result result = MusicArtistAlias.Create( + "Freddie Mercury", + Optional.Some("Mercury, Freddie"), + Optional.Some("Artist name"), + Optional.Some("en"), + isPrimary: true, + Optional.Some(beginDate), + Optional.Some(endDate), + isEnded: true); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Freddie Mercury", result.Value.Name); + Assert.Equal(Optional.Some("Mercury, Freddie"), result.Value.SortName); + Assert.Equal(Optional.Some("Artist name"), result.Value.Type); + Assert.Equal(Optional.Some("en"), result.Value.Locale); + Assert.True(result.Value.IsPrimary); + Assert.Equal(Optional.Some(beginDate), result.Value.BeginDate); + Assert.Equal(Optional.Some(endDate), result.Value.EndDate); + Assert.True(result.Value.IsEnded); + } + + [Fact] + public void Create_WhenNameHasSurroundingWhitespace_ShouldTrimIt() + { + // Act + Result result = MusicArtistAlias.Create( + " Freddie Mercury ", + Optional.None(), + Optional.None(), + Optional.None(), + isPrimary: false, + Optional.None(), + Optional.None(), + isEnded: false); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Freddie Mercury", result.Value.Name); + } + + [Theory] + [InlineData(null)] // null alias name + [InlineData("")] // empty alias name + [InlineData(" ")] // whitespace alias name + public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + { + // Act + Result result = MusicArtistAlias.Create( + name!, + Optional.None(), + Optional.None(), + Optional.None(), + isPrimary: false, + Optional.None(), + Optional.None(), + isEnded: false); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistAliasNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Create_WhenOptionalValuesAreAbsent_ShouldCreateAliasWithoutThem() + { + // Act + Result result = MusicArtistAlias.Create( + "Freddie Mercury", + Optional.None(), + Optional.None(), + Optional.None(), + isPrimary: false, + Optional.None(), + Optional.None(), + isEnded: false); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.SortName.HasValue); + Assert.False(result.Value.Type.HasValue); + Assert.False(result.Value.Locale.HasValue); + Assert.False(result.Value.BeginDate.HasValue); + Assert.False(result.Value.EndDate.HasValue); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create( + name: firstAlias.Name, + sortName: firstAlias.SortName, + type: firstAlias.Type, + locale: firstAlias.Locale, + isPrimary: firstAlias.IsPrimary, + beginDate: firstAlias.BeginDate, + endDate: firstAlias.EndDate, + isEnded: firstAlias.IsEnded); + + // Assert + Assert.Equal(firstAlias, secondAlias); + } + + [Fact] + public void Equals_WithDifferentName_ShouldReturnFalse() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(name: "Freddie Mercury"); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(name: "Farrokh Bulsara"); + + // Assert + Assert.NotEqual(firstAlias, secondAlias); + } + + [Fact] + public void Equals_WithDifferentSortName_ShouldReturnFalse() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(sortName: Optional.Some("Mercury, Freddie")); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(sortName: Optional.Some("Bulsara, Farrokh")); + + // Assert + Assert.NotEqual(firstAlias, secondAlias); + } + + [Fact] + public void Equals_WithDifferentType_ShouldReturnFalse() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(type: Optional.Some("Artist name")); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(type: Optional.Some("Search hint")); + + // Assert + Assert.NotEqual(firstAlias, secondAlias); + } + + [Fact] + public void Equals_WithDifferentLocale_ShouldReturnFalse() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(locale: Optional.Some("en")); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(locale: Optional.Some("fr")); + + // Assert + Assert.NotEqual(firstAlias, secondAlias); + } + + [Fact] + public void Equals_WithDifferentIsPrimary_ShouldReturnFalse() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(isPrimary: true); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(isPrimary: false); + + // Assert + Assert.NotEqual(firstAlias, secondAlias); + } + + [Fact] + public void Equals_WithDifferentBeginDate_ShouldReturnFalse() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(beginDate: Optional.Some(new DateOnly(1970, 1, 1))); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(beginDate: Optional.Some(new DateOnly(1980, 1, 1))); + + // Assert + Assert.NotEqual(firstAlias, secondAlias); + } + + [Fact] + public void Equals_WithDifferentEndDate_ShouldReturnFalse() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(endDate: Optional.Some(new DateOnly(1991, 1, 1))); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(endDate: Optional.Some(new DateOnly(2000, 1, 1))); + + // Assert + Assert.NotEqual(firstAlias, secondAlias); + } + + [Fact] + public void Equals_WithDifferentIsEnded_ShouldReturnFalse() + { + // Arrange + MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(isEnded: true); + + // Act + MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(isEnded: false); + + // Assert + Assert.NotEqual(firstAlias, secondAlias); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataTests.cs new file mode 100644 index 00000000..aae8ca7b --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataTests.cs @@ -0,0 +1,230 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryPathMetadataTests +{ + private readonly MusicLibraryPathMetadataFixture _musicLibraryPathMetadataFixture = new(); + private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new(); + + [Fact] + public void FromParsedLibraryPath_WhenAllValuesAreCaptured_ShouldMapAllFields() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Queen", + [LibraryPathPartKind.ReleaseType] = "Album", + [LibraryPathPartKind.ReleaseYear] = "1975", + [LibraryPathPartKind.ReleaseName] = "A Night at the Opera", + [LibraryPathPartKind.TrackNumber] = "11", + [LibraryPathPartKind.DiscNumber] = "1", + [LibraryPathPartKind.TrackName] = "Bohemian Rhapsody" + }); + + // Act + MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath); + + // Assert + Assert.Equal("Queen", result.ArtistName.Value); + Assert.Equal(MusicReleaseType.Album, result.ReleaseType.Value); + Assert.Equal(1975, result.ReleaseYear.Value); + Assert.Equal("A Night at the Opera", result.ReleaseName.Value); + Assert.Equal(11, result.TrackNumber.Value); + Assert.Equal(1, result.DiscNumber.Value); + Assert.Equal("Bohemian Rhapsody", result.TrackTitle.Value); + } + + [Fact] + public void FromParsedLibraryPath_WhenReleaseTypeIsRecognized_ShouldParseItCaseInsensitively() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.ReleaseType] = "album" + }); + + // Act + MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath); + + // Assert + Assert.True(result.ReleaseType.HasValue); + Assert.Equal(MusicReleaseType.Album, result.ReleaseType.Value); + } + + [Fact] + public void FromParsedLibraryPath_WhenReleaseTypeIsNotRecognized_ShouldFallBackToOther() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.ReleaseType] = "not a release type" + }); + + // Act + MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath); + + // Assert + Assert.True(result.ReleaseType.HasValue); + Assert.Equal(MusicReleaseType.Other, result.ReleaseType.Value); + } + + [Fact] + public void FromParsedLibraryPath_WhenReleaseTypeIsAbsent_ShouldLeaveItUnset() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Queen" + }); + + // Act + MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath); + + // Assert + Assert.False(result.ReleaseType.HasValue); + } + + [Fact] + public void FromParsedLibraryPath_WhenValuesAreAbsent_ShouldLeaveThemUnset() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(includeValues: false); + + // Act + MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath); + + // Assert + Assert.False(result.ArtistName.HasValue); + Assert.False(result.ReleaseType.HasValue); + Assert.False(result.ReleaseYear.HasValue); + Assert.False(result.ReleaseName.HasValue); + Assert.False(result.TrackNumber.HasValue); + Assert.False(result.DiscNumber.HasValue); + Assert.False(result.TrackTitle.HasValue); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(); + + // Act + MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create( + artistName: firstMetadata.ArtistName.Value, + releaseType: firstMetadata.ReleaseType.Value, + releaseYear: firstMetadata.ReleaseYear.Value, + releaseName: firstMetadata.ReleaseName.Value, + trackNumber: firstMetadata.TrackNumber.Value, + discNumber: firstMetadata.DiscNumber.Value, + trackTitle: firstMetadata.TrackTitle.Value); + + // Assert + Assert.Equal(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentArtistName_ShouldReturnFalse() + { + // Arrange + MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(artistName: "Queen"); + + // Act + MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(artistName: "Pink Floyd"); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentReleaseType_ShouldReturnFalse() + { + // Arrange + MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseType: MusicReleaseType.Album); + + // Act + MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseType: MusicReleaseType.Single); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentReleaseYear_ShouldReturnFalse() + { + // Arrange + MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseYear: 1975); + + // Act + MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseYear: 1980); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentReleaseName_ShouldReturnFalse() + { + // Arrange + MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseName: "A Night at the Opera"); + + // Act + MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseName: "The Game"); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentTrackNumber_ShouldReturnFalse() + { + // Arrange + MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(trackNumber: 11); + + // Act + MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(trackNumber: 12); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentDiscNumber_ShouldReturnFalse() + { + // Arrange + MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(discNumber: 1); + + // Act + MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(discNumber: 2); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentTrackTitle_ShouldReturnFalse() + { + // Arrange + MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(trackTitle: "Bohemian Rhapsody"); + + // Act + MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(trackTitle: "Love of My Life"); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWorkTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWorkTests.cs new file mode 100644 index 00000000..020214b7 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicWorkTests.cs @@ -0,0 +1,201 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicWorkTests +{ + private readonly MusicWorkFixture _musicWorkFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateWorkWithAllPropertiesSet() + { + // Arrange + MusicBrainzId workId = _musicBrainzIdFixture.Create(value: Guid.Parse("f0e9c1a2-0000-0000-0000-000000000000")); + LanguageInfo language = _languageInfoFixture.Create(languageCode: "en", languageName: "English"); + + // Act + Result result = MusicWork.Create( + workId, + "Bohemian Rhapsody", + Optional.Some("Song"), + [language], + ["T1234567890"]); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(workId, result.Value.MusicBrainzWorkId); + Assert.Equal("Bohemian Rhapsody", result.Value.Title); + Assert.Equal(Optional.Some("Song"), result.Value.Type); + Assert.Equal([language], result.Value.Languages); + Assert.Equal(["T1234567890"], result.Value.Iswcs); + } + + [Fact] + public void Create_WhenTitleHasSurroundingWhitespace_ShouldTrimIt() + { + // Act + Result result = MusicWork.Create( + _musicBrainzIdFixture.Create(), + " Bohemian Rhapsody ", + Optional.None(), + [], + []); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Bohemian Rhapsody", result.Value.Title); + } + + [Theory] + [InlineData(null)] // null work title + [InlineData("")] // empty work title + [InlineData(" ")] // whitespace work title + public void Create_WhenTitleIsNullOrWhitespace_ShouldReturnError(string? title) + { + // Act + Result result = MusicWork.Create( + _musicBrainzIdFixture.Create(), + title!, + Optional.None(), + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.WorkTitleCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Create_WhenOptionalAndCollectionValuesAreAbsent_ShouldCreateWorkWithoutThem() + { + // Act + Result result = MusicWork.Create( + _musicBrainzIdFixture.Create(), + "Bohemian Rhapsody", + Optional.None(), + [], + []); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Type.HasValue); + Assert.Empty(result.Value.Languages); + Assert.Empty(result.Value.Iswcs); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + MusicWork firstWork = _musicWorkFixture.Create(); + + // Act + MusicWork secondWork = _musicWorkFixture.Create( + musicBrainzWorkId: firstWork.MusicBrainzWorkId, + title: firstWork.Title, + type: firstWork.Type, + languages: [.. firstWork.Languages], + iswcs: [.. firstWork.Iswcs]); + + // Assert + Assert.Equal(firstWork, secondWork); + } + + [Fact] + public void Equals_WithDifferentMusicBrainzWorkId_ShouldReturnFalse() + { + // Arrange + MusicWork firstWork = _musicWorkFixture.Create(musicBrainzWorkId: _musicBrainzIdFixture.Create(value: Guid.Parse("11111111-1111-1111-1111-111111111111"))); + + // Act + MusicWork secondWork = _musicWorkFixture.Create(musicBrainzWorkId: _musicBrainzIdFixture.Create(value: Guid.Parse("22222222-2222-2222-2222-222222222222"))); + + // Assert + Assert.NotEqual(firstWork, secondWork); + } + + [Fact] + public void Equals_WithDifferentTitle_ShouldReturnFalse() + { + // Arrange + MusicWork firstWork = _musicWorkFixture.Create(title: "Bohemian Rhapsody"); + + // Act + MusicWork secondWork = _musicWorkFixture.Create(title: "Love of My Life"); + + // Assert + Assert.NotEqual(firstWork, secondWork); + } + + [Fact] + public void Equals_WithDifferentType_ShouldReturnFalse() + { + // Arrange + MusicWork firstWork = _musicWorkFixture.Create(type: Optional.Some("Song")); + + // Act + MusicWork secondWork = _musicWorkFixture.Create(type: Optional.Some("Instrumental")); + + // Assert + Assert.NotEqual(firstWork, secondWork); + } + + [Fact] + public void Equals_WithDifferentLanguages_ShouldReturnFalse() + { + // Arrange + LanguageInfo english = _languageInfoFixture.Create(languageCode: "en", languageName: "English"); + LanguageInfo french = _languageInfoFixture.Create(languageCode: "fr", languageName: "French"); + MusicWork firstWork = _musicWorkFixture.Create(languages: [english]); + + // Act + MusicWork secondWork = _musicWorkFixture.Create(languages: [french]); + + // Assert + Assert.NotEqual(firstWork, secondWork); + } + + [Fact] + public void Equals_WithDifferentIswcs_ShouldReturnFalse() + { + // Arrange + MusicWork firstWork = _musicWorkFixture.Create(iswcs: ["T1234567890"]); + + // Act + MusicWork secondWork = _musicWorkFixture.Create(iswcs: ["T0987654321"]); + + // Assert + Assert.NotEqual(firstWork, secondWork); + } + + [Fact] + public void Equals_WithDifferentLanguageOrder_ShouldReturnFalse() + { + // Arrange + LanguageInfo english = _languageInfoFixture.Create(languageCode: "en", languageName: "English"); + LanguageInfo french = _languageInfoFixture.Create(languageCode: "fr", languageName: "French"); + MusicWork firstWork = _musicWorkFixture.Create(languages: [english, french]); + + // Act + MusicWork secondWork = _musicWorkFixture.Create(languages: [french, english]); + + // Assert + Assert.NotEqual(firstWork, secondWork); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs index 8bf0cae6..b5e976bd 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs @@ -44,6 +44,7 @@ public class FileSystemStructureSeedServiceTests // Arrange _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); _mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books")); + _mockPathService.CombinePath(_rootPath, "music").Returns(Path.Combine(_rootPath, "music")); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(false); _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.Success(FileSystemPathId.Create(Path.Combine(_rootPath, callInfo.ArgAt(1))).Value)); @@ -53,8 +54,11 @@ public class FileSystemStructureSeedServiceTests // Assert Assert.True(result.IsSuccess); - _mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any()); - _mockDirectoryProviderService.Received(2).CreateDirectory(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.Received(3).DirectoryExists(Arg.Any()); + _mockDirectoryProviderService.Received(3).CreateDirectory(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any(), "libraries"); + _mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any(), "books"); + _mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any(), "music"); } [Fact] @@ -63,6 +67,7 @@ public class FileSystemStructureSeedServiceTests // Arrange _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); _mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books")); + _mockPathService.CombinePath(_rootPath, "music").Returns(Path.Combine(_rootPath, "music")); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(true); // Act @@ -70,7 +75,7 @@ public class FileSystemStructureSeedServiceTests // Assert Assert.True(result.IsSuccess); - _mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any()); + _mockDirectoryProviderService.Received(3).DirectoryExists(Arg.Any()); _mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs index 13260534..a61eca6c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs @@ -817,4 +817,76 @@ public class PathServiceTests Assert.False(result); _mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any(), Arg.Any()); } + + [Theory] + [InlineData('\\', @"C:\Music\Queen\Bohemian Rhapsody.mp3", "Bohemian Rhapsody.mp3")] // Windows separated path + [InlineData('/', "/music/queen/bohemian-rhapsody.mp3", "bohemian-rhapsody.mp3")] // Unix separated path + public void GetFileName_WhenPathHasDirectories_ShouldReturnTheLastSegment(char separator, string path, string expectedFileName) + { + // Arrange + _mockPathStrategy.PathSeparator.Returns(separator); + + // Act + string result = _sut.GetFileName(path); + + // Assert + Assert.Equal(expectedFileName, result); + } + + [Theory] + [InlineData('\\')] // Windows separated path + [InlineData('/')] // Unix separated path + public void GetFileName_WhenPathHasNoDirectory_ShouldReturnThePath(char separator) + { + // Arrange + _mockPathStrategy.PathSeparator.Returns(separator); + + // Act + string result = _sut.GetFileName("Bohemian Rhapsody.mp3"); + + // Assert + Assert.Equal("Bohemian Rhapsody.mp3", result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void GetFileName_WhenPathIsNullOrEmpty_ShouldReturnThePath(string? path) + { + // Act + string result = _sut.GetFileName(path!); + + // Assert + Assert.Equal(path, result); + } + + [Theory] + [InlineData('\\', @"C:\Music\Queen\Bohemian Rhapsody.mp3", "Bohemian Rhapsody")] // Windows separated path + [InlineData('/', "/music/queen/bohemian-rhapsody.mp3", "bohemian-rhapsody")] // Unix separated path + public void GetFileNameWithoutExtension_WhenPathHasDirectories_ShouldReturnTheFileNameWithoutItsExtension(char separator, string path, string expectedFileName) + { + // Arrange + _mockPathStrategy.PathSeparator.Returns(separator); + + // Act + string result = _sut.GetFileNameWithoutExtension(path); + + // Assert + Assert.Equal(expectedFileName, result); + } + + [Theory] + [InlineData('\\')] // Windows separated path + [InlineData('/')] // Unix separated path + public void GetFileNameWithoutExtension_WhenFileNameHasNoExtension_ShouldReturnTheFileName(char separator) + { + // Arrange + _mockPathStrategy.PathSeparator.Returns(separator); + + // Act + string result = _sut.GetFileNameWithoutExtension("Bohemian Rhapsody"); + + // Assert + Assert.Equal("Bohemian Rhapsody", result); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs index b5b7cef3..26070afc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs @@ -26,7 +26,7 @@ public class ThumbnailTests byte[] bytes = [1, 2, 3, 4, 5]; // Act - Thumbnail thumbnail = new(type, bytes); + Thumbnail thumbnail = _thumbnailFixture.Create(type, bytes); // Assert Assert.Equal(type, thumbnail.Type); @@ -38,7 +38,7 @@ public class ThumbnailTests { // Arrange Thumbnail thumbnail1 = _thumbnailFixture.Create(); - Thumbnail thumbnail2 = new(thumbnail1.Type, thumbnail1.Bytes); + Thumbnail thumbnail2 = _thumbnailFixture.Create(thumbnail1.Type, thumbnail1.Bytes); // Act bool result = thumbnail1.Equals(thumbnail2); @@ -80,7 +80,7 @@ public class ThumbnailTests { // Arrange Thumbnail thumbnail1 = _thumbnailFixture.Create(); - Thumbnail thumbnail2 = new(thumbnail1.Type, thumbnail1.Bytes); + Thumbnail thumbnail2 = _thumbnailFixture.Create(thumbnail1.Type, thumbnail1.Bytes); // Act int hashCode1 = thumbnail1.GetHashCode(); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs index 0a6d35fa..8b5af5d2 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; @@ -51,6 +52,7 @@ public class LibraryTests canDownloadMetadataFromWeb: false, shouldSaveMetadataInMediaDirectories: true, shouldSkipUnchangedDirectoriesDuringScan: true, + LibraryPathTemplate.Empty(), scanIds); // Assert @@ -89,6 +91,7 @@ public class LibraryTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + LibraryPathTemplate.Empty(), scanIds); // Assert @@ -115,6 +118,7 @@ public class LibraryTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + LibraryPathTemplate.Empty(), []); // Assert @@ -150,6 +154,7 @@ public class LibraryTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + LibraryPathTemplate.Empty(), []); // Assert @@ -177,6 +182,7 @@ public class LibraryTests canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, + LibraryPathTemplate.Empty(), []); // Assert diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartTests.cs new file mode 100644 index 00000000..0617d1bd --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartTests.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartTests +{ + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + + [Fact] + public void Create_WhenKindIsSeparator_ShouldCreateSeparatorWithoutRepresentation() + { + // Act + Result result = LibraryPathPart.Create(LibraryPathPartKind.Separator, "/", isOptional: false); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(LibraryPathPartKind.Separator, result.Value.Kind); + Assert.Equal(string.Empty, result.Value.Representation); + } + + [Fact] + public void Create_WhenKindIsLiteralWithText_ShouldCreateLiteralWithThatRepresentation() + { + // Act + Result result = LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", isOptional: false); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(LibraryPathPartKind.Literal, result.Value.Kind); + Assert.Equal(" - ", result.Value.Representation); + } + + [Theory] + [InlineData(null)] // the representation is absent + [InlineData("")] // the representation is empty + [InlineData(" ")] // the representation is whitespace + public void Create_WhenKindIsNotSeparatorAndRepresentationIsEmpty_ShouldReturnLiteralCannotBeEmptyError(string? representation) + { + // Act + Result result = LibraryPathPart.Create(LibraryPathPartKind.Literal, representation, isOptional: false); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Create_WhenTypedPartContainsSinglePlaceholder_ShouldCreateThePart() + { + // Act + Result result = LibraryPathPart.Create(LibraryPathPartKind.Artist, "{0}", isOptional: false); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("{0}", result.Value.Representation); + } + + [Fact] + public void Create_WhenTypedPartContainsFixedWidthPlaceholder_ShouldCreateThePart() + { + // Act + Result result = LibraryPathPart.Create(LibraryPathPartKind.TrackNumber, "Disc {0:00}", isOptional: true); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Disc {0:00}", result.Value.Representation); + Assert.True(result.Value.IsOptional); + } + + [Theory] + [InlineData("no placeholder")] // the mask carries no value placeholder + [InlineData("{0} {0}")] // the mask carries more than one value placeholder + public void Create_WhenTypedPartDoesNotContainExactlyOnePlaceholder_ShouldReturnError(string representation) + { + // Act + Result result = LibraryPathPart.Create(LibraryPathPartKind.Artist, representation, isOptional: false); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError); + } + + [Fact] + public void Create_WhenLiteralContainsNoPlaceholder_ShouldCreateThePart() + { + // Act + Result result = LibraryPathPart.Create(LibraryPathPartKind.Literal, "Disk ", isOptional: false); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Disk ", result.Value.Representation); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true); + + // Act + LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true); + + // Assert + Assert.Equal(firstPart, secondPart); + } + + [Fact] + public void Equals_WithDifferentKind_ShouldReturnFalse() + { + // Arrange + LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + + // Act + LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}", isOptional: false); + + // Assert + Assert.NotEqual(firstPart, secondPart); + } + + [Fact] + public void Equals_WithDifferentRepresentation_ShouldReturnFalse() + { + // Arrange + LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + + // Act + LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "Artist: {0}", isOptional: false); + + // Assert + Assert.NotEqual(firstPart, secondPart); + } + + [Fact] + public void Equals_WithDifferentIsOptional_ShouldReturnFalse() + { + // Arrange + LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: false); + + // Act + LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true); + + // Assert + Assert.NotEqual(firstPart, secondPart); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateTests.cs new file mode 100644 index 00000000..e9a51976 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateTests +{ + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + + [Fact] + public void Create_WhenCalledWithParts_ShouldCreateTemplateWithThoseParts() + { + // Arrange + LibraryPathTemplate template = _libraryPathTemplateFixture.Create(); + + // Act + LibraryPathTemplate result = LibraryPathTemplate.Create(template.Parts); + + // Assert + Assert.Equal(template.Parts, result.Parts); + Assert.False(result.IsEmpty); + } + + [Fact] + public void Empty_WhenCalled_ShouldCreateTemplateWithoutParts() + { + // Act + LibraryPathTemplate result = LibraryPathTemplate.Empty(); + + // Assert + Assert.Empty(result.Parts); + Assert.True(result.IsEmpty); + } + + [Fact] + public void Create_WhenSourceCollectionIsLaterModified_ShouldNotAffectTheTemplate() + { + // Arrange + List sourceParts = [.. _libraryPathTemplateFixture.Create().Parts]; + int originalCount = sourceParts.Count; + + // Act + LibraryPathTemplate template = LibraryPathTemplate.Create(sourceParts); + sourceParts.Clear(); + + // Assert + Assert.Equal(originalCount, template.Parts.Count); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create(); + + // Act + LibraryPathTemplate secondTemplate = LibraryPathTemplate.Create(firstTemplate.Parts); + + // Assert + Assert.Equal(firstTemplate, secondTemplate); + } + + [Fact] + public void Equals_WithDifferentParts_ShouldReturnFalse() + { + // Arrange + LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create(); + + // Act + LibraryPathTemplate secondTemplate = _libraryPathTemplateFixture.Create(); + + // Assert + Assert.NotEqual(firstTemplate, secondTemplate); + } + + [Fact] + public void Equals_WhenBothTemplatesAreEmpty_ShouldReturnTrue() + { + // Act + LibraryPathTemplate firstTemplate = LibraryPathTemplate.Empty(); + LibraryPathTemplate secondTemplate = LibraryPathTemplate.Empty(); + + // Assert + Assert.Equal(firstTemplate, secondTemplate); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs new file mode 100644 index 00000000..4e125f6a --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs @@ -0,0 +1,497 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateServiceTests +{ + private readonly ILibraryPathPartCatalog _mockCatalog = Substitute.For(); + private readonly LibraryPathTemplateService _sut; + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryPathTemplateServiceTests() + { + _mockCatalog.SupportedLibraryType.Returns(LibraryType.Music); + _sut = new LibraryPathTemplateService([_mockCatalog]); + } + + [Fact] + public void GetDefaultTemplate_WhenCatalogExists_ShouldReturnTheCatalogDefaultTemplate() + { + // Arrange + LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(); + _mockCatalog.GetDefaultTemplate().Returns(defaultTemplate); + + // Act + LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Music); + + // Assert + Assert.Equal(defaultTemplate, result); + } + + [Fact] + public void GetDefaultTemplate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnAnEmptyTemplate() + { + // Act + LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Book); + + // Assert + Assert.True(result.IsEmpty); + } + + [Fact] + public void ResolveTemplate_WhenProvidedPartsAreEmpty_ShouldReturnTheCatalogDefaultTemplate() + { + // Arrange + SetupCatalog(); + LibraryPathTemplate defaultTemplate = CreateMusicTemplate(); + _mockCatalog.GetDefaultTemplate().Returns(defaultTemplate); + + // Act + Result result = _sut.ResolveTemplate(LibraryType.Music, []); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(defaultTemplate, result.Value); + _mockCatalog.Received(1).GetDefaultTemplate(); + } + + [Fact] + public void ResolveTemplate_WhenProvidedPartsAreEmptyAndNoCatalogExists_ShouldReturnAnEmptyTemplate() + { + // Act + Result result = _sut.ResolveTemplate(LibraryType.Book, []); + + // Assert + Assert.False(result.IsFailure); + Assert.True(result.Value.IsEmpty); + } + + [Fact] + public void ResolveTemplate_WhenProvidedPartsAreNotEmpty_ShouldReturnATemplateWithThoseParts() + { + // Arrange + SetupCatalog(); + LibraryPathPart providedPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: false); + + // Act + Result result = _sut.ResolveTemplate(LibraryType.Music, [providedPart]); + + // Assert + Assert.False(result.IsFailure); + LibraryPathPart pathPart = Assert.Single(result.Value.Parts); + Assert.Equal(LibraryPathPartKind.Artist, pathPart.Kind); + Assert.Equal("{0}", pathPart.Representation); + Assert.False(pathPart.IsOptional); + _mockCatalog.DidNotReceive().GetDefaultTemplate(); + } + + [Fact] + public void ResolveTemplate_WhenProvidedPartsAreNotSupportedByTheCatalog_ShouldReturnError() + { + // Arrange + SetupCatalog( + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty) + ]); + LibraryPathPart releaseNamePart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.ReleaseName, + representation: "{0}", + isOptional: false); + + // Act + Result result = _sut.ResolveTemplate(LibraryType.Music, [releaseNamePart]); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError); + } + + [Fact] + public void ResolveTemplate_WhenNoCatalogExistsForTheLibraryTypeAndPartsAreProvided_ShouldReturnNotSupportedError() + { + // Arrange + LibraryPathPart artistPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: false); + + // Act + Result result = _sut.ResolveTemplate(LibraryType.Book, [artistPart]); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError); + } + + [Fact] + public void Validate_WhenTemplateIsEmpty_ShouldReturnSuccess() + { + // Act + Result result = _sut.Validate(LibraryType.Music, LibraryPathTemplate.Empty()); + + // Assert + Assert.False(result.IsFailure); + } + + [Fact] + public void Validate_WhenTemplateIsEmptyAndNoCatalogExists_ShouldReturnSuccess() + { + // Act + Result result = _sut.Validate(LibraryType.Book, LibraryPathTemplate.Empty()); + + // Assert + Assert.False(result.IsFailure); + } + + [Fact] + public void Validate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnNotSupportedError() + { + // Act + Result result = _sut.Validate(LibraryType.Book, CreateMusicTemplate()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError); + } + + [Fact] + public void Validate_WhenPartKindIsNotSupportedByTheCatalog_ShouldReturnError() + { + // Arrange + SetupCatalog(definitions: + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}") + ]); + LibraryPathTemplate template = _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}") + ]); + + // Act + Result result = _sut.Validate(LibraryType.Music, template); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError); + } + + [Fact] + public void Validate_WhenAllPartKindsAreSupportedByTheCatalog_ShouldReturnSuccess() + { + // Arrange + SetupCatalog(); + LibraryPathTemplate template = CreateMusicTemplate(); + + // Act + Result result = _sut.Validate(LibraryType.Music, template); + + // Assert + Assert.False(result.IsFailure); + } + + [Theory] + [InlineData("")] // the relative path is empty + [InlineData(" ")] // the relative path is whitespace + public void Parse_WhenRelativePathIsEmpty_ShouldReturnNull(string relativePath) + { + // Act + Result> result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.HasValue); + } + + [Fact] + public void Parse_WhenTemplateIsEmpty_ShouldReturnNull() + { + // Act + Result> result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.HasValue); + } + + [Fact] + public void Parse_WhenTemplateIsNotSupportedForTheLibraryType_ShouldReturnError() + { + // Act + Result> result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/'); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError); + } + + [Fact] + public void Parse_WhenPathMatchesTheTemplate_ShouldReturnTheCapturedValues() + { + // Arrange + SetupCatalog(); + LibraryPathTemplate template = CreateMusicTemplate(); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/'); + + // Assert + Assert.False(result.IsFailure); + ParsedLibraryPath parsedPath = result.Value.Value; + Assert.Equal("Pink Floyd", parsedPath.GetString(LibraryPathPartKind.Artist).Value); + Assert.Equal(1973, parsedPath.GetInt(LibraryPathPartKind.ReleaseYear).Value); + Assert.Equal("Time", parsedPath.GetString(LibraryPathPartKind.TrackName).Value); + Assert.Equal("mp3", parsedPath.GetString(LibraryPathPartKind.Extension).Value); + } + + [Fact] + public void Parse_WhenPathDoesNotMatchTheTemplate_ShouldReturnNull() + { + // Arrange + SetupCatalog(); + LibraryPathTemplate template = CreateMusicTemplate(); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.HasValue); + } + + [Fact] + public void Parse_WhenIntegerPartHasAFixedWidth_ShouldCaptureIt() + { + // Arrange + SetupCatalog( + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}") + ]); + LibraryPathTemplate template = _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}") + ]); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(7, result.Value.Value.GetInt(LibraryPathPartKind.TrackNumber).Value); + } + + [Fact] + public void Parse_WhenIntegerPartDoesNotMatchTheFixedWidth_ShouldReturnNull() + { + // Arrange + SetupCatalog( + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}") + ]); + LibraryPathTemplate template = _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}") + ]); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.HasValue); + } + + [Fact] + public void Parse_WhenYearPartHasAFourDigitValue_ShouldCaptureIt() + { + // Arrange + SetupCatalog( + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}") + ]); + LibraryPathTemplate template = _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}") + ]); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "1973", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1973, result.Value.Value.GetInt(LibraryPathPartKind.ReleaseYear).Value); + } + + [Fact] + public void Parse_WhenYearPartDoesNotHaveAFourDigitValue_ShouldReturnNull() + { + // Arrange + SetupCatalog( + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}") + ]); + LibraryPathTemplate template = _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}") + ]); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "73", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.HasValue); + } + + [Fact] + public void Parse_WhenAnOptionalRunIsAbsent_ShouldStillMatchThePath() + { + // Arrange + SetupCatalog( + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}") + ]); + LibraryPathTemplate template = _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true) + ]); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value); + Assert.False(result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue); + } + + [Fact] + public void Parse_WhenAnOptionalRunIsPresent_ShouldCaptureIt() + { + // Arrange + SetupCatalog( + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}") + ]); + LibraryPathTemplate template = _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true) + ]); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value); + Assert.Equal(2, result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).Value); + } + + [Fact] + public void Parse_WhenTheSameKindAppearsMoreThanOnce_ShouldKeepTheFirstCapture() + { + // Arrange + SetupCatalog( + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Author, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Title, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty) + ]); + LibraryPathTemplate template = _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Title, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}") + ]); + + // Act + Result> result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Tolkien", result.Value.Value.GetString(LibraryPathPartKind.Author).Value); + } + + /// + /// Sets up the mock catalog to return a music-like set of part definitions and a default template. + /// + /// Optional. The part definitions the catalog returns. When omitted, a standard music set is used. + private void SetupCatalog(IReadOnlyList? definitions = null) + { + _mockCatalog.GetPartDefinitions().Returns(definitions ?? + [ + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"), + _libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Extension, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}") + ]); + } + + /// + /// Creates a music-like path template whose parts are all supported by the standard music set of definitions. + /// + /// The created path template. + private LibraryPathTemplate CreateMusicTemplate() + { + return _libraryPathTemplateFixture.Create( + [ + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackName, representation: "{0}"), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: "."), + _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Extension, representation: "{0}") + ]); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs index 9a3f743b..e495f603 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -33,6 +34,23 @@ public class MediaLibraryScannerFactoryTests Assert.Same(expectedScanner, scanner); } + [Fact] + public void CreateLibraryScanner_WhenLibraryTypeIsMusic_ShouldReturnMusicLibraryTypeScanner() + { + // Arrange + IMusicLibraryTypeScanner expectedScanner = Substitute.For(); + ServiceCollection services = new(); + services.AddSingleton(expectedScanner); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + MediaLibraryScannerFactory sut = new(serviceProvider); + + // Act + IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Music); + + // Assert + Assert.Same(expectedScanner, scanner); + } + [Theory] [InlineData(LibraryType.EBook)] // eBook scanner is not implemented [InlineData(LibraryType.ComicBook)] // comic book scanner is not implemented @@ -55,7 +73,6 @@ public class MediaLibraryScannerFactoryTests [InlineData(LibraryType.InterviewVideo)] // interview video scanner is not implemented [InlineData(LibraryType.CoverSongVideo)] // cover song video scanner is not implemented [InlineData(LibraryType.PodcastVideo)] // podcast video scanner is not implemented - [InlineData(LibraryType.Music)] // music scanner is not implemented [InlineData(LibraryType.Audiobook)] // audiobook scanner is not implemented [InlineData(LibraryType.LiveRecordingAudio)] // live recording audio scanner is not implemented [InlineData(LibraryType.InterviewAudio)] // interview audio scanner is not implemented diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionTests.cs new file mode 100644 index 00000000..7a34ae0d --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartDefinitionTests +{ + private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Act + LibraryPathPartDefinition definition = new(LibraryPathPartKind.TrackNumber, LibraryPathValueType.Integer, "{0:00}", isOptionalByDefault: true); + + // Assert + Assert.Equal(LibraryPathPartKind.TrackNumber, definition.Kind); + Assert.Equal(LibraryPathValueType.Integer, definition.ValueType); + Assert.Equal("{0:00}", definition.DefaultRepresentation); + Assert.True(definition.IsOptionalByDefault); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.Artist, + valueType: LibraryPathValueType.Text, + defaultRepresentation: "{0}", + isOptionalByDefault: false); + + // Act + LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.Artist, + valueType: LibraryPathValueType.Text, + defaultRepresentation: "{0}", + isOptionalByDefault: false); + + // Assert + Assert.Equal(firstDefinition, secondDefinition); + } + + [Fact] + public void Equals_WithDifferentKind_ShouldReturnFalse() + { + // Arrange + LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.Artist, + valueType: LibraryPathValueType.Text, + defaultRepresentation: "{0}"); + + // Act + LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.ReleaseName, + valueType: LibraryPathValueType.Text, + defaultRepresentation: "{0}"); + + // Assert + Assert.NotEqual(firstDefinition, secondDefinition); + } + + [Fact] + public void Equals_WithDifferentValueType_ShouldReturnFalse() + { + // Arrange + LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.TrackNumber, + valueType: LibraryPathValueType.Integer, + defaultRepresentation: "{0}"); + + // Act + LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.TrackNumber, + valueType: LibraryPathValueType.Text, + defaultRepresentation: "{0}"); + + // Assert + Assert.NotEqual(firstDefinition, secondDefinition); + } + + [Fact] + public void Equals_WithDifferentDefaultRepresentation_ShouldReturnFalse() + { + // Arrange + LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.ReleaseYear, + valueType: LibraryPathValueType.Year, + defaultRepresentation: "{0}"); + + // Act + LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.ReleaseYear, + valueType: LibraryPathValueType.Year, + defaultRepresentation: "Year {0}"); + + // Assert + Assert.NotEqual(firstDefinition, secondDefinition); + } + + [Fact] + public void Equals_WithDifferentIsOptionalByDefault_ShouldReturnFalse() + { + // Arrange + LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.DiscNumber, + valueType: LibraryPathValueType.Integer, + defaultRepresentation: "{0:00}", + isOptionalByDefault: false); + + // Act + LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create( + kind: LibraryPathPartKind.DiscNumber, + valueType: LibraryPathValueType.Integer, + defaultRepresentation: "{0:00}", + isOptionalByDefault: true); + + // Assert + Assert.NotEqual(firstDefinition, secondDefinition); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathTests.cs new file mode 100644 index 00000000..cd0e3197 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathTests.cs @@ -0,0 +1,230 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ParsedLibraryPathTests +{ + private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new(); + + [Fact] + public void Create_WhenCalledWithValues_ShouldExposeThoseValues() + { + // Arrange + Dictionary values = new() + { + [LibraryPathPartKind.Artist] = "Pink Floyd", + [LibraryPathPartKind.TrackName] = "Time" + }; + + // Act + ParsedLibraryPath result = ParsedLibraryPath.Create(values); + + // Assert + Assert.Equal(2, result.Values.Count); + Assert.Equal("Pink Floyd", result.Values[LibraryPathPartKind.Artist]); + Assert.Equal("Time", result.Values[LibraryPathPartKind.TrackName]); + } + + [Fact] + public void GetString_WhenKindIsCaptured_ShouldReturnTheTrimmedValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = " Pink Floyd " + }); + + // Act + Optional result = parsedPath.GetString(LibraryPathPartKind.Artist); + + // Assert + Assert.True(result.HasValue); + Assert.Equal("Pink Floyd", result.Value); + } + + [Fact] + public void GetString_WhenKindIsNotCaptured_ShouldReturnNoValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Pink Floyd" + }); + + // Act + Optional result = parsedPath.GetString(LibraryPathPartKind.TrackName); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void GetString_WhenCapturedValueIsWhitespace_ShouldReturnNoValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = " " + }); + + // Act + Optional result = parsedPath.GetString(LibraryPathPartKind.Artist); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void GetInt_WhenKindIsCapturedWithAnInteger_ShouldReturnTheValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.ReleaseYear] = "1973" + }); + + // Act + Optional result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear); + + // Assert + Assert.True(result.HasValue); + Assert.Equal(1973, result.Value); + } + + [Fact] + public void GetInt_WhenKindIsNotCaptured_ShouldReturnNoValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Pink Floyd" + }); + + // Act + Optional result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void GetInt_WhenCapturedValueIsNotAnInteger_ShouldReturnNoValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.ReleaseYear] = "not a year" + }); + + // Act + Optional result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void ToDictionary_WhenCalled_ShouldReturnAllCapturedValues() + { + // Arrange + Dictionary values = new() + { + [LibraryPathPartKind.Artist] = "Pink Floyd", + [LibraryPathPartKind.TrackName] = "Time" + }; + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values); + + // Act + IReadOnlyDictionary result = parsedPath.ToDictionary(); + + // Assert + Assert.Equal(values, result); + } + + [Fact] + public void ToDictionary_WhenCalled_ShouldReturnACopy() + { + // Arrange + Dictionary values = new() + { + [LibraryPathPartKind.Artist] = "Pink Floyd" + }; + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values); + + // Act + IReadOnlyDictionary result = parsedPath.ToDictionary(); + + // Assert + Assert.NotSame(values, result); + } + + [Fact] + public void Equals_WithSameValuesInDifferentOrder_ShouldReturnTrue() + { + // Arrange + ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Pink Floyd", + [LibraryPathPartKind.TrackName] = "Time" + }); + + // Act + ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.TrackName] = "Time", + [LibraryPathPartKind.Artist] = "Pink Floyd" + }); + + // Assert + Assert.Equal(firstPath, secondPath); + } + + [Fact] + public void Equals_WithDifferentValues_ShouldReturnFalse() + { + // Arrange + ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Pink Floyd" + }); + + // Act + ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Queen" + }); + + // Assert + Assert.NotEqual(firstPath, secondPath); + } + + [Fact] + public void Equals_WithDifferentKeys_ShouldReturnFalse() + { + // Arrange + ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Pink Floyd" + }); + + // Act + ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Title] = "Pink Floyd" + }); + + // Assert + Assert.NotEqual(firstPath, secondPath); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs index 27de1b25..49092a2e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs @@ -80,7 +80,7 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true); + Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true, shouldAggregateArtworkWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true); // Assert Assert.False(result.IsFailure); @@ -117,7 +117,7 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); + Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); // Assert Assert.True(result.IsFailure); @@ -132,7 +132,7 @@ public class UserSettingsTests UserSettingsId id = _userSettingsIdFixture.Create(); // Act - Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: true); + Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: true); // Assert Assert.False(result.IsFailure); @@ -149,7 +149,7 @@ public class UserSettingsTests UserSettingsId id = _userSettingsIdFixture.Create(); // Act - Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); + Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); // Assert Assert.True(result.IsFailure); @@ -163,7 +163,7 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true); + Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true, shouldAggregateArtworkWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true); // Assert Assert.False(result.IsFailure); @@ -185,7 +185,7 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); + Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: false); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieTests.cs index c62d157f..412bf701 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieTests.cs @@ -72,7 +72,7 @@ public class MovieTests List ratings = [CreateRating(4.5m)]; // Act - Movie movie = new(id, metadata, contributors, ratings); + Movie movie = _movieFixture.Create(id, metadata, contributors, ratings); // Assert Assert.Equal(id, movie.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs index 14b6bd6d..cb15846c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalogTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalogTests.cs new file mode 100644 index 00000000..8316f980 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalogTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLibraryPathPartCatalogTests +{ + private readonly BookLibraryPathPartCatalog _sut = new(); + + [Fact] + public void SupportedLibraryType_WhenCalled_ShouldReturnBook() + { + // Act + LibraryType result = _sut.SupportedLibraryType; + + // Assert + Assert.Equal(LibraryType.Book, result); + } + + [Fact] + public void GetPartDefinitions_WhenCalled_ShouldReturnTheExpectedDefinitions() + { + // Act + IReadOnlyList result = _sut.GetPartDefinitions(); + + // Assert + Assert.Equal(8, result.Count); + + Assert.Equal(LibraryPathPartKind.Literal, result[0].Kind); + Assert.Equal(LibraryPathValueType.None, result[0].ValueType); + Assert.Equal(string.Empty, result[0].DefaultRepresentation); + Assert.False(result[0].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind); + Assert.Equal(LibraryPathValueType.None, result[1].ValueType); + Assert.Equal(string.Empty, result[1].DefaultRepresentation); + Assert.False(result[1].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.Author, result[2].Kind); + Assert.Equal(LibraryPathValueType.Text, result[2].ValueType); + Assert.Equal("{0}", result[2].DefaultRepresentation); + Assert.False(result[2].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.Title, result[3].Kind); + Assert.Equal(LibraryPathValueType.Text, result[3].ValueType); + Assert.Equal("{0}", result[3].DefaultRepresentation); + Assert.False(result[3].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.Series, result[4].Kind); + Assert.Equal(LibraryPathValueType.Text, result[4].ValueType); + Assert.Equal("{0}", result[4].DefaultRepresentation); + Assert.True(result[4].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.SeriesNumber, result[5].Kind); + Assert.Equal(LibraryPathValueType.Integer, result[5].ValueType); + Assert.Equal("{0}", result[5].DefaultRepresentation); + Assert.True(result[5].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.BookId, result[6].Kind); + Assert.Equal(LibraryPathValueType.Integer, result[6].ValueType); + Assert.Equal("{0}", result[6].DefaultRepresentation); + Assert.False(result[6].IsOptionalByDefault); + + Assert.Equal(LibraryPathPartKind.Extension, result[7].Kind); + Assert.Equal(LibraryPathValueType.Text, result[7].ValueType); + Assert.Equal("{0}", result[7].DefaultRepresentation); + Assert.False(result[7].IsOptionalByDefault); + } + + [Fact] + public void GetDefaultTemplate_WhenCalled_ShouldReturnTheExpectedParts() + { + // Act + IReadOnlyList result = _sut.GetDefaultTemplate().Parts; + + // Assert + Assert.Equal(12, result.Count); + + Assert.Equal(LibraryPathPartKind.Author, result[0].Kind); + Assert.Equal("{0}", result[0].Representation); + Assert.False(result[0].IsOptional); + + Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind); + Assert.Equal(string.Empty, result[1].Representation); + Assert.False(result[1].IsOptional); + + Assert.Equal(LibraryPathPartKind.Title, result[2].Kind); + Assert.Equal("{0}", result[2].Representation); + Assert.False(result[2].IsOptional); + + Assert.Equal(LibraryPathPartKind.Literal, result[3].Kind); + Assert.Equal(" (", result[3].Representation); + Assert.False(result[3].IsOptional); + + Assert.Equal(LibraryPathPartKind.BookId, result[4].Kind); + Assert.Equal("{0}", result[4].Representation); + Assert.False(result[4].IsOptional); + + Assert.Equal(LibraryPathPartKind.Literal, result[5].Kind); + Assert.Equal(")", result[5].Representation); + Assert.False(result[5].IsOptional); + + Assert.Equal(LibraryPathPartKind.Separator, result[6].Kind); + Assert.Equal(string.Empty, result[6].Representation); + Assert.False(result[6].IsOptional); + + Assert.Equal(LibraryPathPartKind.Title, result[7].Kind); + Assert.Equal("{0}", result[7].Representation); + Assert.False(result[7].IsOptional); + + Assert.Equal(LibraryPathPartKind.Literal, result[8].Kind); + Assert.Equal(" - ", result[8].Representation); + Assert.False(result[8].IsOptional); + + Assert.Equal(LibraryPathPartKind.Author, result[9].Kind); + Assert.Equal("{0}", result[9].Representation); + Assert.False(result[9].IsOptional); + + Assert.Equal(LibraryPathPartKind.Literal, result[10].Kind); + Assert.Equal(".", result[10].Representation); + Assert.False(result[10].IsOptional); + + Assert.Equal(LibraryPathPartKind.Extension, result[11].Kind); + Assert.Equal("{0}", result[11].Representation); + Assert.False(result[11].IsOptional); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj index 61b45860..208e108e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs new file mode 100644 index 00000000..97aa0d77 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs @@ -0,0 +1,190 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Networking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Networking; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PublicHostRedirectHandlerTests +{ + [Fact] + public async Task SendAsync_WhenTheInitialRequestHostIsPublic_ShouldSendTheRequest() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => new HttpResponseMessage(HttpStatusCode.OK)); + using HttpClient client = CreateClient(innerHandler); + + // Act + HttpResponseMessage response = await client.GetAsync("https://example.com/cover.jpg"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(1, innerHandler.CallCount); + } + + [Theory] + [InlineData("http://127.0.0.1/cover.jpg")] // the IPv4 loopback address + [InlineData("http://localhost/cover.jpg")] // the loopback host name + [InlineData("http://[::1]/cover.jpg")] // the IPv6 loopback address + [InlineData("http://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint + [InlineData("http://10.0.0.5/cover.jpg")] // a private class A address + [InlineData("http://172.16.0.1/cover.jpg")] // a private class B address + [InlineData("http://192.168.1.10/cover.jpg")] // a private class C address + public async Task SendAsync_WhenTheInitialRequestHostIsPrivateOrLocal_ShouldThrowAndNotSendTheRequest(string url) + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => new HttpResponseMessage(HttpStatusCode.OK)); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync(url); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(0, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheInitialRequestRedirectsToAPublicHttpsHost_ShouldFollowIt() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + if (callIndex == 1) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/download/mbid-1/index.json"); + return redirect; + } + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using HttpClient client = CreateClient(innerHandler); + + // Act + HttpResponseMessage response = await client.GetAsync("https://coverartarchive.org/release/1"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(2, innerHandler.CallCount); + Assert.Equal("archive.org", innerHandler.Requests[1].RequestUri!.Host); + } + + [Theory] + [InlineData("http://archive.org/index.json")] // a downgrade of a trusted host to plain HTTP + [InlineData("https://127.0.0.1/index.json")] // the IPv4 loopback address + [InlineData("https://localhost/index.json")] // the loopback host name + [InlineData("https://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint + [InlineData("https://10.0.0.5/index.json")] // a private class A address + [InlineData("https://192.168.1.10/index.json")] // a private class C address + public async Task SendAsync_WhenTheInitialRequestRedirectsToADisallowedTarget_ShouldThrow(string location) + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri(location); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync("https://coverartarchive.org/release/1"); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(1, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheRequestIsRedirectedTooManyTimes_ShouldThrow() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/loop/index.json"); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync("https://coverartarchive.org/release/1"); + } + + // Assert + await Assert.ThrowsAsync(Act); + // The initial request plus the maximum number of followed redirects are sent before the loop is detected. + Assert.Equal(6, innerHandler.CallCount); + } + + /// + /// Creates an whose requests are sent through the handler under test, wrapping the provided inner handler. + /// + /// The handler that answers the requests that reach the network. + /// The created client. + private static HttpClient CreateClient(HttpMessageHandler innerHandler) + { + PublicHostRedirectHandler handler = new() { InnerHandler = innerHandler }; + return new HttpClient(handler); + } + + /// + /// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent. + /// + [ExcludeFromCodeCoverage] + private sealed class StubHttpMessageHandler : HttpMessageHandler + { + private readonly Func _responseFactory; + private int _callCount; + + /// + /// Gets the requests that were sent through the handler. + /// + public List Requests { get; } = []; + + /// + /// Gets the number of requests that were sent through the handler. + /// + public int CallCount => _callCount; + + /// + /// Initializes a new instance of the class. + /// + /// The factory that produces the response of a request, given the request and its one based call index. + public StubHttpMessageHandler(Func responseFactory) + { + _responseFactory = responseFactory; + } + + /// + /// Sends the provided request, producing its response through the configured factory. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response produced for the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + int callIndex = Interlocked.Increment(ref _callCount); + Requests.Add(request); + return Task.FromResult(_responseFactory(request, callIndex)); + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs new file mode 100644 index 00000000..0d2e3097 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Networking; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Networking; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PublicHostValidatorTests +{ + [Theory] + [InlineData("coverartarchive.org")] // a public host name + [InlineData("example.com")] // a public host name + [InlineData("8.8.8.8")] // a public IPv4 address + [InlineData("1.1.1.1")] // a public IPv4 address + [InlineData("172.15.0.1")] // the address just below the private class B range + [InlineData("172.32.0.1")] // the address just above the private class B range + [InlineData("2606:4700:4700::1111")] // a public IPv6 address + public void IsPublicHost_WhenTheHostIsPublic_ShouldReturnTrue(string host) + { + // Act + bool result = PublicHostValidator.IsPublicHost(host); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData("")] // an empty host + [InlineData(" ")] // only white space + [InlineData("localhost")] // the loopback host name + [InlineData("LOCALHOST")] // the loopback host name, upper cased + [InlineData("127.0.0.1")] // the IPv4 loopback address + [InlineData("::1")] // the IPv6 loopback address + [InlineData("[::1]")] // the IPv6 loopback address, bracketed like a URI host + [InlineData("0.0.0.0")] // the unspecified IPv4 address + [InlineData("[::]")] // the unspecified IPv6 address + [InlineData("169.254.169.254")] // the link local cloud metadata endpoint + [InlineData("10.0.0.5")] // a private class A address + [InlineData("172.16.0.1")] // the lower bound of the private class B range + [InlineData("172.31.255.255")] // the upper bound of the private class B range + [InlineData("192.168.1.10")] // a private class C address + [InlineData("100.64.0.1")] // the lower bound of the carrier grade NAT range + [InlineData("100.127.255.255")] // the upper bound of the carrier grade NAT range + [InlineData("fc00::1")] // the IPv6 unique local range + [InlineData("fe80::1")] // the IPv6 link local range + public void IsPublicHost_WhenTheHostIsPrivateOrLocal_ShouldReturnFalse(string host) + { + // Act + bool result = PublicHostValidator.IsPublicHost(host); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/ImageTypeUtilitiesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/ImageTypeUtilitiesTests.cs new file mode 100644 index 00000000..8ce853ee --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/ImageTypeUtilitiesTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Common.Utilities; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Utilities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ImageTypeUtilitiesTests +{ + [Theory] + [InlineData(ImageType.BMP, "bmp")] // bitmap image + [InlineData(ImageType.GIF, "gif")] // graphics interchange format + [InlineData(ImageType.PNG, "png")] // portable network graphics + [InlineData(ImageType.TIFF, "tiff")] // tagged image file format + [InlineData(ImageType.PICT, "pct")] // macintosh picture + [InlineData(ImageType.ICO, "ico")] // icon format + [InlineData(ImageType.PSD, "psd")] // photoshop document + [InlineData(ImageType.JPEG2000, "jp2")] // jpeg 2000 + [InlineData(ImageType.AVIF, "avif")] // av1 image file format + [InlineData(ImageType.WEBP, "webp")] // web picture format + [InlineData(ImageType.TGA, "tga")] // truevision tga + [InlineData(ImageType.SVG, "svg")] // scalable vector graphics + public void ToFileExtension_WhenTypeIsRecognized_ShouldReturnConventionalExtension(ImageType imageType, string expectedExtension) + { + // Act + string result = imageType.ToFileExtension(); + + // Assert + Assert.Equal(expectedExtension, result); + } + + [Theory] + [InlineData(ImageType.JPEG)] // joint photographic experts group + [InlineData(ImageType.JPEG_CANON)] // canon-specific jpeg + [InlineData(ImageType.JPEG_UNKNOWN)] // unknown jpeg + public void ToFileExtension_WhenTypeIsAnyJpeg_ShouldReturnJpg(ImageType imageType) + { + // Act + string result = imageType.ToFileExtension(); + + // Assert + Assert.Equal("jpg", result); + } + + [Fact] + public void ToFileExtension_WhenTypeIsNotARecognizedImage_ShouldReturnBin() + { + // Act + string result = ImageType.None.ToFileExtension(); + + // Assert + Assert.Equal("bin", result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs index f103f529..2f4f76cf 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs @@ -21,6 +21,7 @@ namespace Lumina.Infrastructure.UnitTests.Common.Validation; public class ValidationOptionsTests { private readonly IFixture _fixture; + private readonly ValidationOptionsFixture _validationOptionsFixture = new(); /// /// Initializes a new instance of the class. @@ -35,7 +36,7 @@ public class ValidationOptionsTests { // Arrange string name = _fixture.Create(); - ValidationOptionsFixture options = _fixture.Create(); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); IValidator validator = Substitute.For>(); validator.Validate(options).Returns([]); ValidationOptions sut = new(name, validator); @@ -55,7 +56,7 @@ public class ValidationOptionsTests // Arrange string name = _fixture.Create(); string differentName = _fixture.Create(); - ValidationOptionsFixture options = _fixture.Create(); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); IValidator validator = Substitute.For>(); ValidationOptions sut = new(name, validator); @@ -71,7 +72,7 @@ public class ValidationOptionsTests public void Validate_WhenNullName_ShouldValidateOptions() { // Arrange - ValidationOptionsFixture options = _fixture.Create(); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); IValidator validator = Substitute.For>(); validator.Validate(options).Returns([]); ValidationOptions sut = new(null, validator); @@ -105,7 +106,7 @@ public class ValidationOptionsTests { // Arrange string name = _fixture.Create(); - ValidationOptionsFixture options = _fixture.Create(); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); IValidator validator = Substitute.For>(); List validationFailures = [ diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs new file mode 100644 index 00000000..f79aef01 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs @@ -0,0 +1,252 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkServiceTests +{ + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly IHttpClientFactory _mockHttpClientFactory; + private readonly IOptions _mockMediaSettingsOptions; + private readonly MusicArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + + _mockHttpClientFactory = Substitute.For(); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music"); + _mockMediaSettingsOptions = Substitute.For>(); + _mockMediaSettingsOptions.Value.Returns(mediaSettings); + + _sut = new MusicArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg"); + MockPathBuilding(); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound() + { + // Arrange + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg"); + MockPathBuilding(); + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + } + + [Fact] + public void DeleteAlbumArtwork_WhenListingTheArtworkFilesFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files")); + + // Act + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + + [Fact] + public void DeleteAlbumArtwork_WhenCalled_ShouldDeleteEveryFileInTheAlbumDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); + FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg")); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([coverFileId, bookletFileId])); + _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); + + // Act + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).DeleteFile(coverFileId); + _mockFileProviderService.Received(1).DeleteFile(bookletFileId); + } + + [Fact] + public void DeleteAlbumArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError() + { + // Arrange + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(Errors.FileSystemManagement.InvalidPath); + + // Act + Result result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album"); + + // Assert + Assert.True(result.IsFailure); + _mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any(), true); + } + + [Fact] + public void DeleteAlbumArtwork_WhenBuildingTheDirectoryPathFails_ShouldReturnTheError() + { + // Arrange + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Errors.FileSystemManagement.InvalidPath); + + // Act + Result result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album"); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + /// + /// Stubs the path service so that building the artwork directory paths succeeds. + /// + private void MockPathBuilding() + { + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); + }); + + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + } + + /// + /// Stubs the path and file system services so that the artwork is stored into the given directory. + /// + /// The file system path of the directory into which the artwork is stored. + private void MockArtworkDirectoryStubs(string artworkDirectoryPath) + { + MockPathBuilding(); + + // Every directory except the artwork directory itself already exists, so that only the final directory is created. + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(callInfo => Result.From(!string.Equals(callInfo.Arg().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase))); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())))); + + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + } + + /// + /// Builds the file system path of the directory that the artwork of the album is stored into. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The expected file system path of the album artwork directory. + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "music", + $"{libraryName}-{libraryId}", + artistName, + $"{albumTitle}-{albumId}"); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs new file mode 100644 index 00000000..ecd0616c --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMetadataAggregatorTests +{ + private readonly ArtistMetadataDtoFixture _artistMetadataDtoFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + + [Fact] + public void Merge_WhenMergingArtistMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond() + { + // Arrange + MediaContributorDto firstContributor = _mediaContributorDtoFixture.Create(); + MediaContributorDto secondContributor = _mediaContributorDtoFixture.Create(); + ArtistMetadataDto first = _artistMetadataDtoFixture.Create(name: "First", includeCountry: false, contributors: [firstContributor], genres: []); + ArtistMetadataDto second = _artistMetadataDtoFixture.Create(name: "Second", country: "CA", contributors: [secondContributor], genres: []); + + // Act + ArtistMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First", merged.Name); + Assert.Equal("CA", merged.Country); + Assert.Equal(2, merged.Contributors!.Count); + Assert.Contains(merged.Contributors, contributor => contributor == firstContributor); + Assert.Contains(merged.Contributors, contributor => contributor == secondContributor); + } + + [Fact] + public void Merge_WhenFirstArtistHasTheValue_ShouldNotTakeTheSecondValue() + { + // Arrange + ArtistMetadataDto first = _artistMetadataDtoFixture.Create(name: "First", country: "US", genres: [], contributors: []); + ArtistMetadataDto second = _artistMetadataDtoFixture.Create(name: "Second", country: "CA", genres: [], contributors: []); + + // Act + ArtistMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First", merged.Name); + Assert.Equal("US", merged.Country); + } + + [Fact] + public void Merge_WhenMergingAlbumMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond() + { + // Arrange + AlbumMetadataDto first = _albumMetadataDtoFixture.Create(title: "First", includeBarcode: false, includeReleaseInfo: false); + AlbumMetadataDto second = _albumMetadataDtoFixture.Create(title: "Second", barcode: "1234567890123"); + + // Act + AlbumMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First", merged.Title); + Assert.Equal("1234567890123", merged.Barcode); + Assert.NotNull(merged.ReleaseInfo); + } + + [Fact] + public void Merge_WhenMergingAudioMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond() + { + // Arrange + AudioMetadataDto first = _audioMetadataDtoFixture.Create(title: "First", includeDurationInSeconds: false); + AudioMetadataDto second = _audioMetadataDtoFixture.Create(title: "Second", durationInSeconds: 360); + + // Act + AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First", merged.Title); + Assert.Equal(360, merged.DurationInSeconds); + } + + [Fact] + public void Merge_WhenTheFirstMetadataHasOnlyAReleaseYearAndTheSecondHasAReleaseDate_ShouldDeriveTheYearFromTheDate() + { + // Arrange + // The tags of a compilation provide a release year without a full date, while MusicBrainz provides the original release date of the recording. + ReleaseInfoDto firstReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseYear: 1981); + ReleaseInfoDto secondReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(1975, 10, 31), originalReleaseYear: 1975); + AudioMetadataDto first = _audioMetadataDtoFixture.Create(releaseInfo: firstReleaseInfo); + AudioMetadataDto second = _audioMetadataDtoFixture.Create(releaseInfo: secondReleaseInfo); + + // Act + AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + // The merged date and year must describe the same point in time, otherwise the release information would be rejected when applied. + Assert.NotNull(merged.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 10, 31), merged.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, merged.ReleaseInfo.OriginalReleaseYear); + } + + [Fact] + public void Merge_WhenBothAudioMetadataHaveIsrcs_ShouldUnionThemWithoutDuplicates() + { + // Arrange + AudioMetadataDto first = _audioMetadataDtoFixture.Create(); + AudioMetadataDto second = _audioMetadataDtoFixture.Create(); + AudioMetadataDto mergedInput = first with { Isrcs = [.. first.Isrcs!.Concat(second.Isrcs!)] }; + + // Act + AudioMetadataDto merged = MusicMetadataAggregator.Merge(mergedInput, second); + + // Assert + Assert.Equal(mergedInput.Isrcs!.Select(isrc => isrc.Value).Distinct(StringComparer.OrdinalIgnoreCase).Count(), merged.Isrcs!.Count); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs new file mode 100644 index 00000000..00981ae7 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs @@ -0,0 +1,379 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicFileSystemDiscoveryJobTests +{ + private const string ROOT_PATH = @"C:\Music"; + private const string AUDIO_FILE_PATH = @"C:\Music\song.mp3"; + private const string IMAGE_FILE_PATH = @"C:\Music\cover.jpg"; + + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; + private readonly IDirectoryScanFingerprintRepository _mockFingerprintRepository; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MusicFileSystemDiscoveryJob _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + /// + /// Initializes a new instance of the class. + /// + public MusicFileSystemDiscoveryJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); + _mockFingerprintRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); + _mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockFingerprintRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockServiceProvider.GetService(typeof(IFileProviderService)).Returns(_mockFileProviderService); + _mockServiceProvider.GetService(typeof(IDirectoryProviderService)).Returns(_mockDirectoryProviderService); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + // Default stubs that keep the happy path working, overridden per test where needed. + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Created); + _mockFingerprintRepository.UpsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Updated); + _mockFileProviderService.GetSize(Arg.Any()).Returns(Result.From(0)); + _mockFileProviderService.GetLastWriteTime(Arg.Any()).Returns(Result.From(Optional.None())); + _mockDirectoryProviderService.GetLastWriteTime(Arg.Any()).Returns(Result.From(Optional.None())); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to retrieve the library")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryHasAudioFiles_ShouldStageOnlyTheAudioFilesAndComplete() + { + // Arrange + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH, IMAGE_FILE_PATH], subdirectories: []); + _mockFileProviderService.GetSize(Arg.Is(path => path.Path == AUDIO_FILE_PATH)).Returns(Result.From(1234L)); + _mockFileProviderService.GetLastWriteTime(Arg.Is(path => path.Path == AUDIO_FILE_PATH)) + .Returns(Result.From(Optional.Some(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().Path == AUDIO_FILE_PATH + && entities.First().Size == 1234 + && entities.First().LibraryScanId == _scanId.Value + && entities.First().NeedsRehash), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheSubdirectoryHasAudioFiles_ShouldTraverseIntoIt() + { + // Arrange + const string SUBDIRECTORY_PATH = @"C:\Music\Album"; + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [], subdirectories: [SUBDIRECTORY_PATH]); + SetupDirectory(SUBDIRECTORY_PATH, files: [AUDIO_FILE_PATH], subdirectories: []); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && entities.First().Path == AUDIO_FILE_PATH), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFastSkipIsEnabledAndTheDirectoryIsUnchanged_ShouldSkipIt() + { + // Arrange + DateTime lastWriteTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true); + _mockDirectoryProviderService.GetLastWriteTime(Arg.Is(path => path.Path == ROOT_PATH)) + .Returns(Result.From(Optional.Some(lastWriteTime))); + _mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Dictionary + { + [ROOT_PATH] = _directoryScanFingerprintEntityFixture.Create(libraryId: _libraryId.Value, path: ROOT_PATH, lastWriteTimeUtc: lastWriteTime) + })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + _mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any(), true); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFastSkipIsEnabledAndTheDirectoryChanged_ShouldStoreAFingerprint() + { + // Arrange + DateTime lastWriteTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true); + _mockDirectoryProviderService.GetLastWriteTime(Arg.Is(path => path.Path == ROOT_PATH)) + .Returns(Result.From(Optional.Some(lastWriteTime))); + _mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Dictionary + { + [ROOT_PATH] = _directoryScanFingerprintEntityFixture.Create(libraryId: _libraryId.Value, path: ROOT_PATH, lastWriteTimeUtc: lastWriteTime.AddDays(-1)) + })); + SetupDirectory(ROOT_PATH, files: [], subdirectories: []); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockFingerprintRepository.Received(1).UpsertRangeAsync( + Arg.Is>(fingerprints => fingerprints.Count == 1 && fingerprints.First().Path == ROOT_PATH), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFileSizeAndLastWriteTimeCannotBeRead_ShouldStageTheFileWithDefaults() + { + // Arrange + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []); + _mockFileProviderService.GetSize(Arg.Any()).Returns(Error.Failure("FileSystem.Error", "Failed to read the size")); + _mockFileProviderService.GetLastWriteTime(Arg.Any()).Returns(Error.Failure("FileSystem.Error", "Failed to read the last write time")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && entities.First().Size == 0 && entities.First().Ticks == 0), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenReadingTheDirectoryFails_ShouldSkipItAndComplete() + { + // Arrange + SetupLibrary(); + _mockFileProviderService.GetFilePaths(Arg.Any(), true).Returns(Error.Failure("FileSystem.Error", "Failed to read the files")); + _mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Any(), true).Returns(Error.Failure("FileSystem.Error", "Failed to read the subdirectories")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheStagingInsertFails_ShouldMarkJobAsFailed() + { + // Arrange + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []); + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to stage the discovered files")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFingerprintUpsertFails_ShouldMarkJobAsFailed() + { + // Arrange + SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true); + SetupDirectory(ROOT_PATH, files: [], subdirectories: []); + _mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Dictionary())); + _mockFingerprintRepository.UpsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to store the fingerprints")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobIsCompleted_ShouldPublishProgressAndCallTheChildren() + { + // Arrange + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [], subdirectories: []); + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockDomainEventPublisher.Received().PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + /// + /// Stubs the media library reader with a library whose single content location is the test root path. + /// + /// Whether the library skips the directories that have not changed since the last scan. + private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false) + { + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + contentLocations: [ROOT_PATH], + shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Stubs the file and directory providers for the provided directory. + /// + /// The file system path of the directory. + /// The file system paths of the files of the directory. + /// The file system paths of the subdirectories of the directory. + private void SetupDirectory(string directory, string[] files, string[] subdirectories) + { + _mockFileProviderService.GetFilePaths(Arg.Is(path => path.Path == directory), true) + .Returns(Result.From>([.. files.Select(file => PathId(file))])); + _mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Is(path => path.Path == directory), true) + .Returns(Result.From>([.. subdirectories.Select(subdirectoryPath => PathId(subdirectoryPath))])); + } + + /// + /// Creates a file system path id for the provided path. + /// + /// The path to create the id for. + /// The created file system path id. + private static FileSystemPathId PathId(string path) + { + return FileSystemPathId.Create(path).Value; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs new file mode 100644 index 00000000..032222b0 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs @@ -0,0 +1,160 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryPathStructureTests +{ + private readonly IPathService _mockPathService; + private readonly MusicLibraryPathStructure _sut; + + /// + /// Initializes a new instance of the class. + /// + public MusicLibraryPathStructureTests() + { + _mockPathService = Substitute.For(); + _sut = new MusicLibraryPathStructure(_mockPathService); + } + + [Theory] + [InlineData('\\', @"C:\Music\Queen\A Night at the Opera", @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac")] // Windows separated path + [InlineData('/', "/music/queen/a-night-at-the-opera", "/music/queen/a-night-at-the-opera/bohemian-rhapsody.flac")] // Unix separated path + public void GetAlbumDirectory_WhenTheTrackIsInTheAlbumDirectory_ShouldReturnTheTrackDirectory(char separator, string albumDirectory, string trackPath) + { + // Arrange + _mockPathService.PathSeparator.Returns(separator); + + // Act + string result = _sut.GetAlbumDirectory(trackPath); + + // Assert + Assert.Equal(albumDirectory, result); + } + + [Theory] + [InlineData('\\', "Disc 1")] // canonical disc directory name, Windows separated path + [InlineData('\\', "disc 2")] // lowercase disc directory name, Windows separated path + [InlineData('\\', "CD3")] // compact disc directory name, Windows separated path + [InlineData('\\', "disk4")] // disk directory name, Windows separated path + [InlineData('/', "Disc 1")] // canonical disc directory name, Unix separated path + [InlineData('/', "disc 2")] // lowercase disc directory name, Unix separated path + [InlineData('/', "CD3")] // compact disc directory name, Unix separated path + [InlineData('/', "disk4")] // disk directory name, Unix separated path + public void GetAlbumDirectory_WhenTheTrackIsInADiscDirectory_ShouldReturnTheParentAlbumDirectory(char separator, string discDirectoryName) + { + // Arrange + _mockPathService.PathSeparator.Returns(separator); + string albumDirectory = string.Join(separator, "music", "queen", "a-night-at-the-opera"); + string trackPath = string.Join(separator, albumDirectory, discDirectoryName, "bohemian-rhapsody.flac"); + + // Act + string result = _sut.GetAlbumDirectory(trackPath); + + // Assert + Assert.Equal(albumDirectory, result); + } + + [Theory] + [InlineData('\\')] // Windows separated path + [InlineData('/')] // Unix separated path + public void GetAlbumDirectory_WhenTheDirectoryIsNotADiscDirectory_ShouldReturnTheTrackDirectory(char separator) + { + // Arrange + _mockPathService.PathSeparator.Returns(separator); + string albumDirectory = string.Join(separator, "music", "queen", "live"); + string trackPath = string.Join(separator, albumDirectory, "bohemian-rhapsody.flac"); + + // Act + string result = _sut.GetAlbumDirectory(trackPath); + + // Assert + Assert.Equal(albumDirectory, result); + } + + [Fact] + public void GetAlbumDirectory_WhenThePathIsNullOrEmpty_ShouldReturnTheProvidedPath() + { + // Act + string nullResult = _sut.GetAlbumDirectory(null!); + string emptyResult = _sut.GetAlbumDirectory(string.Empty); + + // Assert + Assert.Null(nullResult); + Assert.Equal(string.Empty, emptyResult); + } + + [Theory] + [InlineData('\\')] // Windows separated path + [InlineData('/')] // Unix separated path + public void GetAlbumDirectory_WhenThePathHasNoDirectory_ShouldReturnTheProvidedPath(char separator) + { + // Arrange + _mockPathService.PathSeparator.Returns(separator); + const string FILE_NAME_ONLY = "Bohemian Rhapsody.flac"; + + // Act + string result = _sut.GetAlbumDirectory(FILE_NAME_ONLY); + + // Assert + Assert.Equal(FILE_NAME_ONLY, result); + } + + [Theory] + [InlineData('\\', "Album")] // canonical release type directory, Windows separated path + [InlineData('\\', "album")] // lowercase release type directory, Windows separated path + [InlineData('/', "Album")] // canonical release type directory, Unix separated path + [InlineData('/', "album")] // lowercase release type directory, Unix separated path + public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsAReleaseType_ShouldReturnIt(char separator, string releaseTypeDirectoryName) + { + // Arrange + _mockPathService.PathSeparator.Returns(separator); + string trackPath = string.Join(separator, "music", "queen", releaseTypeDirectoryName, "a-night-at-the-opera", "bohemian-rhapsody.flac"); + + // Act + string? result = _sut.GetReleaseTypeDirectoryName(trackPath); + + // Assert + Assert.Equal(releaseTypeDirectoryName, result); + } + + [Theory] + [InlineData('\\')] // Windows separated path + [InlineData('/')] // Unix separated path + public void GetReleaseTypeDirectoryName_WhenTheAlbumIsMultiDisc_ShouldReturnTheReleaseTypeDirectory(char separator) + { + // Arrange + _mockPathService.PathSeparator.Returns(separator); + string trackPath = string.Join(separator, "music", "queen", "Album", "a-night-at-the-opera", "Disc 1", "bohemian-rhapsody.flac"); + + // Act + string? result = _sut.GetReleaseTypeDirectoryName(trackPath); + + // Assert + Assert.Equal("Album", result); + } + + [Theory] + [InlineData('\\')] // Windows separated path + [InlineData('/')] // Unix separated path + public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsNotAReleaseType_ShouldReturnNull(char separator) + { + // Arrange + _mockPathService.PathSeparator.Returns(separator); + string trackPath = string.Join(separator, "music", "queen", "a-night-at-the-opera", "bohemian-rhapsody.flac"); + + // Act + string? result = _sut.GetReleaseTypeDirectoryName(trackPath); + + // Assert + Assert.Null(result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs new file mode 100644 index 00000000..3c5e645b --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs @@ -0,0 +1,609 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMediaLibraryScanArtworkEnricherTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly IMusicArtworkService _mockMusicArtworkService; + private readonly IFileHashService _mockFileHashService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly IPathService _mockPathService; + private readonly TestArtworkProvider _artistProvider; + private readonly TestArtworkProvider _albumProvider; + private readonly MusicMediaLibraryScanArtworkEnricher _sut; + private readonly ServiceProvider _serviceProvider; + private readonly Guid _artistPluginId = Guid.NewGuid(); + private readonly Guid _albumPluginId = Guid.NewGuid(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicMediaLibraryScanArtworkEnricherTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockArtworkProviderConfigurationRepository = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + + _artistProvider = new TestArtworkProvider { Name = "Artist Provider", RequiresWebAccess = false }; + _albumProvider = new TestArtworkProvider { Name = "Album Provider", RequiresWebAccess = false }; + + _mockMusicArtworkService = Substitute.For(); + _mockFileHashService = Substitute.For(); + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('/'); + + // The enricher resolves the keyed artwork providers from the scope of the service provider, and specializes them by the lookup they accept, + // so a real container is used to honor the keyed registration of the typed providers. + ServiceCollection services = new(); + services.AddScoped(_ => _mockUnitOfWork); + services.AddScoped(_ => _mockDomainEventPublisher); + services.AddSingleton(_mockMusicArtworkService); + services.AddSingleton(_mockFileHashService); + services.AddKeyedSingleton(_artistPluginId, _artistProvider); + services.AddKeyedSingleton(_albumPluginId, _albumProvider); + _serviceProvider = services.BuildServiceProvider(); + + _sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService(), NullLogger.Instance, new MusicLibraryPathStructure(_mockPathService)); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + + // Default stubs that keep the happy path working, overridden per test where needed. + SetupLibrary(); + SetupConfiguration(); + _mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + _mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(0)); + _mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(0)); + _mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary())); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + SetupSuccessArtworkStorage(); + } + + [Fact] + public void SupportedLibraryType_WhenCalled_ShouldReturnMusic() + { + // Act + LibraryType result = _sut.SupportedLibraryType; + + // Assert + Assert.Equal(LibraryType.Music, result); + } + + [Fact] + public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment() + { + // Arrange + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment() + { + // Arrange + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Provider.Error", "Failed to read the configurations")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess() + { + // Arrange + SetupLibrary(canDownloadMetadataFromWeb: false); + _artistProvider.RequiresWebAccess = true; + _albumProvider.RequiresWebAccess = true; + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve() + { + // Arrange + SetupLibrary(canDownloadMetadataFromWeb: false); + _artistProvider.RequiresWebAccess = true; + AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value); + SetupAlbums(album); + _albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + Assert.Equal(1, _albumProvider.CallCount); + Assert.Equal(0, _artistProvider.CallCount); + } + + [Fact] + public async Task EnrichAsync_WhenTheArtistProviderReturnsArtwork_ShouldStoreAndPersistEnrichedArtistArtwork() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync( + _libraryId.Value, + Arg.Any(), + artist.Name, + Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), + Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any()); + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().OwnerType == MusicArtworkOwnerType.Artist + && entities.First().OwnerId == artist.Id + && entities.First().ArtworkType == ArtworkType.Cover + && entities.First().Ordinal == 0 + && entities.First().Status == ArtworkStatus.Enriched + && entities.First().Provider == "Artist Provider" + && entities.First().FileName == "/media/music/cover.jpg" + && entities.First().ContentHash == 123UL), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheAlbumProviderReturnsArtwork_ShouldStoreAndPersistEnrichedAlbumArtwork() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value); + SetupAlbums(album); + _albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + _libraryId.Value, + album.Id, + Arg.Any(), + Arg.Any(), + album.Title, + Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), + Arg.Any(), + Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any()); + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().OwnerType == MusicArtworkOwnerType.Album + && entities.First().OwnerId == album.Id + && entities.First().Status == ArtworkStatus.Enriched + && entities.First().Provider == "Album Provider"), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheProviderAnswersWithNoArtwork_ShouldMarkTheArtistNotAvailable() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().Status == ArtworkStatus.NotAvailable + && entities.First().FileName == null + && entities.First().Provider == null), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheArtistFailed() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromException>(new HttpRequestException("Transient failure.")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheArtistFailed() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.Error", "Failed to store the artwork")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenClearingTheStoredArtworkFilesFails_ShouldLeaveTheArtistUnresolved() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork files")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenClearingTheStoredArtworkRecordsFails_ShouldLeaveTheArtistUnresolved() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + _mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork records")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheAlbumHasNoMusicBrainzIdentifierAndNoLocalProvider_ShouldLeaveItUnresolved() + { + // Arrange + _albumProvider.RequiresWebAccess = true; + AlbumEntity album = _albumEntityFixture.Create( + libraryId: _libraryId.Value, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false); + SetupAlbums(album); + _albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + Assert.Equal(0, _albumProvider.CallCount); + await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheAlbumCountCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to count the albums")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheAlbumsPageCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(1)); + _mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the albums")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheTrackPathsCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value); + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(1)); + _mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([album])); + _mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the track paths")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to save the changes")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + /// + /// Stubs the media library reader with a library owned by the test user. + /// + /// Whether the library allows downloading data from the web. + private void SetupLibrary(bool canDownloadMetadataFromWeb = true) + { + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + canDownloadMetadataFromWeb: canDownloadMetadataFromWeb); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Stubs the artwork provider configuration reader with one enabled configuration per test plugin. + /// + private void SetupConfiguration() + { + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>( + [ + _libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _artistPluginId, 0), + _libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _albumPluginId, 1) + ])); + } + + /// + /// Stubs the artist reader with a single page holding the provided artists. + /// + /// The artists of the page. + private void SetupArtists(params ArtistEntity[] artists) + { + _mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(artists.Length)); + _mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(artists), + Result.From>([])); + } + + /// + /// Stubs the album reader with a single page holding the provided albums. + /// + /// The albums of the page. + private void SetupAlbums(params AlbumEntity[] albums) + { + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(albums.Length)); + _mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(albums), + Result.From>([])); + Dictionary trackPaths = albums.ToDictionary(album => album.Id, album => "/music/artist/album/track.flac"); + _mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(trackPaths)); + } + + /// + /// Stubs the artwork storage and persistence so that an item is stored successfully. + /// + private void SetupSuccessArtworkStorage() + { + _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/music/cover.jpg")); + _mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/music/cover.jpg")); + _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicArtworkRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Created); + _mockFileHashService.ComputeFileHash(Arg.Any()).Returns(123UL); + } + + /// + /// Deterministic artwork provider for a specific lookup type, used instead of a substitute because the default implementation of + /// cannot be intercepted reliably. + /// + /// The type of the lookup the provider accepts. + private sealed class TestArtworkProvider : IArtworkProvider where TLookup : MetadataLookupDto + { + /// + /// Gets or sets the display name of the artwork provider. + /// + public string Name { get; set; } = string.Empty; + + /// + /// Gets or sets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes { get; set; } = [LibraryType.Music]; + + /// + /// Gets or sets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess { get; set; } + + /// + /// Gets or sets the callback that supplies the artwork of a media item. + /// + public Func>> OnGetArtworkAsync { get; set; } = (_, _) => Task.FromResult>([]); + + /// + /// Gets the number of times the provider was asked for artwork. + /// + public int CallCount { get; private set; } + + /// + /// Gets the artworks of the media item described by . + /// + /// The lookup describing the media item to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artworks of the media item, or an empty collection when no artwork was found. + public Task> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken) + { + CallCount++; + return OnGetArtworkAsync(lookup, cancellationToken); + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs new file mode 100644 index 00000000..1b2a54ac --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs @@ -0,0 +1,190 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMediaLibraryScanItemMaterializerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IMusicLibraryScanItemMetadataRepository _mockStagedMetadataRepository; + private readonly IPathService _mockPathService; + private readonly MusicMediaLibraryScanItemMaterializer _sut; + private readonly MusicLibraryScanItemMetadataEntityFixture _musicLibraryScanItemMetadataEntityFixture = new(); + private readonly List _insertedArtists = []; + private readonly Guid _libraryId = Guid.NewGuid(); + private readonly Guid _scanId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public MusicMediaLibraryScanItemMaterializerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockStagedMetadataRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockStagedMetadataRepository); + + _mockArtistRepository.GetByNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockAlbumRepository.GetByTitleAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockArtistRepository.InsertAsync(Arg.Do(artist => _insertedArtists.Add(artist)), Arg.Any()) + .Returns(Result.From(new Created())); + _mockAlbumRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Created())); + _mockTrackRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Created())); + _mockTrackRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + _mockStagedMetadataRepository.DeleteByScanIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Deleted())); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('/'); + _mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns("track"); + + _sut = new MusicMediaLibraryScanItemMaterializer(new MusicLibraryPathStructure(_mockPathService), _mockPathService); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenTheTracksLiveInDifferentDirectories_ShouldMaterializeOneAlbumPerDirectory() + { + // Arrange + Guid releaseArtistId = Guid.NewGuid(); + Guid firstReleaseId = Guid.NewGuid(); + Guid secondReleaseId = Guid.NewGuid(); + Guid firstRecordingId = Guid.NewGuid(); + Guid secondRecordingId = Guid.NewGuid(); + MusicLibraryScanItemMetadataEntity firstStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Shared Artist Name", + releaseName: "Shared Release Title", + path: "/music/shared-artist/release-one/first.mp3", + musicBrainzArtistId: Guid.NewGuid(), + musicBrainzReleaseArtistId: releaseArtistId, + musicBrainzReleaseId: firstReleaseId, + musicBrainzRecordingId: firstRecordingId); + MusicLibraryScanItemMetadataEntity secondStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Shared Artist Name", + releaseName: "Shared Release Title", + path: "/music/shared-artist/release-two/second.mp3", + musicBrainzArtistId: Guid.NewGuid(), + musicBrainzReleaseArtistId: releaseArtistId, + musicBrainzReleaseId: secondReleaseId, + musicBrainzRecordingId: secondRecordingId); + _mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any()) + .Returns(Result.From>([firstStagedItem, secondStagedItem])); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + // The same artist name groups the items under a single artist, whose identifier is the one of the release artist. + ArtistEntity artist = Assert.Single(_insertedArtists); + Assert.Equal(releaseArtistId, artist.MusicBrainzArtistId); + // The distinct release identifiers keep the identically titled releases apart. + Assert.Equal(2, artist.Albums.Count); + AlbumEntity firstAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == firstReleaseId); + AlbumEntity secondAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == secondReleaseId); + Assert.Equal(firstRecordingId, Assert.Single(firstAlbum.Tracks).MusicBrainzRecordingId); + Assert.Equal(secondRecordingId, Assert.Single(secondAlbum.Tracks).MusicBrainzRecordingId); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenCompilationTracksHaveDifferentTrackArtists_ShouldMaterializeASingleAlbumArtist() + { + // Arrange + Guid variousArtistsId = Guid.NewGuid(); + Guid compilationReleaseId = Guid.NewGuid(); + MusicLibraryScanItemMetadataEntity firstStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Various Artists", + releaseName: "Now That Is Music", + path: "/music/various-artists/now-that-is-music/first.mp3", + musicBrainzArtistId: Guid.NewGuid(), + musicBrainzReleaseArtistId: variousArtistsId, + musicBrainzReleaseId: compilationReleaseId); + MusicLibraryScanItemMetadataEntity secondStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Various Artists", + releaseName: "Now That Is Music", + path: "/music/various-artists/now-that-is-music/second.mp3", + musicBrainzArtistId: Guid.NewGuid(), + musicBrainzReleaseArtistId: variousArtistsId, + musicBrainzReleaseId: compilationReleaseId); + _mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any()) + .Returns(Result.From>([firstStagedItem, secondStagedItem])); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + // The different track artists of the compilation do not split the release artist into several identically named artists. + ArtistEntity artist = Assert.Single(_insertedArtists); + Assert.Equal("Various Artists", artist.Name); + Assert.Equal(variousArtistsId, artist.MusicBrainzArtistId); + AlbumEntity album = Assert.Single(artist.Albums); + Assert.Equal(2, album.Tracks.Count); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenTheTagsDoNotCarryMusicBrainzIds_ShouldGroupByTheNameAndTitle() + { + // Arrange + MusicLibraryScanItemMetadataEntity firstStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Shared Artist Name", + releaseName: "Shared Release Title", + path: "/music/shared-artist/shared-release/first.mp3", + includeMusicBrainzTags: false); + MusicLibraryScanItemMetadataEntity secondStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Shared Artist Name", + releaseName: "Shared Release Title", + path: "/music/shared-artist/shared-release/second.mp3", + includeMusicBrainzTags: false); + _mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any()) + .Returns(Result.From>([firstStagedItem, secondStagedItem])); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + // Without identifiers, the items fall back to the name and the title, so they collapse into a single artist with a single album. + ArtistEntity artist = Assert.Single(_insertedArtists); + AlbumEntity album = Assert.Single(artist.Albums); + Assert.Null(artist.MusicBrainzArtistId); + Assert.Null(album.MusicBrainzReleaseId); + Assert.Equal(2, album.Tracks.Count); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricherTests.cs new file mode 100644 index 00000000..6994dc7e --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricherTests.cs @@ -0,0 +1,326 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMediaLibraryScanMetadataEnricherTests +{ + private const string PROVIDER_A_NAME = "ProviderA"; + private const string PROVIDER_B_NAME = "ProviderB"; + + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly IMetadataProvider _mockProviderA; + private readonly IMetadataProvider _mockProviderB; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ServiceProvider _serviceProvider; + private readonly MusicMediaLibraryScanMetadataEnricher _sut; + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly ArtistMetadataDtoFixture _artistMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public MusicMediaLibraryScanMetadataEnricherTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockMetadataConfigurationRepository = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository); + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(Substitute.For()); + + // Both plugins expose only an artist metadata provider, so that the tests exercise the artist lookup in isolation, without album or track lookups ever reaching a provider. + _mockProviderA = Substitute.For(); + ConfigureProvider(_mockProviderA, PROVIDER_A_NAME); + _mockProviderB = Substitute.For(); + ConfigureProvider(_mockProviderB, PROVIDER_B_NAME); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + + // the configured providers are registered under the plugin Ids they are configured with, the way the host registers plugin provided services + Guid pluginAId = Guid.NewGuid(); + Guid pluginBId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result>.Success( + [ + _libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginAId, rank: 1), + _libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginBId, rank: 2) + ])); + + ServiceCollection services = new(); + services.AddScoped(_ => _mockUnitOfWork); + services.AddScoped(_ => _mockDomainEventPublisher); + services.AddKeyedTransient(pluginAId, (serviceProvider, serviceKey) => _mockProviderA); + services.AddKeyedTransient(pluginBId, (serviceProvider, serviceKey) => _mockProviderB); + _serviceProvider = services.BuildServiceProvider(); + + _sut = new MusicMediaLibraryScanMetadataEnricher(_serviceProvider.GetRequiredService(), NullLogger.Instance); + + _mockArtistRepository.GetArtistsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(1)); + _mockAlbumRepository.GetAlbumsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(1)); + _mockTrackRepository.GetTracksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(1)); + _mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([])); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.From(Result.Success)); + } + + [Fact] + public async Task EnrichAsync_WhenArtistsAlbumsAndTracksNeedEnrichment_ShouldPublishProgressMeasuredInItems() + { + // Arrange + _mockArtistRepository.GetArtistsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(2)); + _mockAlbumRepository.GetAlbumsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(3)); + _mockTrackRepository.GetTracksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(5)); + _mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + // the total is the sum of the artists, the albums and the tracks, and the final update reaches it + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.Progress.CompletedItems == 0 + && domainEvent.Progress.TotalItems == 10), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.Progress.CompletedItems == 10 + && domainEvent.Progress.TotalItems == 10), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheFirstProviderReturnsApplicableMetadata_ShouldNotQueryTheFollowingProviders() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + _mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([artist]), Result>.Success([])); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_A_NAME), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheFirstProviderReturnsNoUsableMetadata_ShouldQueryTheFollowingProviders() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + _mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([artist]), Result>.Success([])); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)null); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_B_NAME), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheMetadataOfTheFirstProviderCannotBeApplied_ShouldQueryTheFollowingProviders() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + _mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([artist]), Result>.Success([])); + // a genre without a name is usable as metadata, but makes the domain conversion of the whole metadata fail + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist", genres: [_genreDtoFixture.Create(includeName: false)])); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_B_NAME), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenSavingFailsWithAUniqueConstraintViolation_ShouldContinueWithTheFollowingArtists() + { + // Arrange + ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: _libraryId.Value, name: "First Artist"); + ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: _libraryId.Value, name: "Second Artist"); + _mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([firstArtist, secondArtist]), Result>.Success([])); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Failure(Errors.Persistence.UniqueConstraintViolation), Result.From(Result.Success)); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + // The first artist's save fails with a unique constraint conflict, which must not abort the scan, so the second artist is still processed. + await _mockUnitOfWork.Received(2).SaveChangesAsync(Arg.Any()); + await _mockArtistRepository.Received(2).UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenAggregationIsEnabled_ShouldQueryEveryProviderAndMergeTheirMetadata() + { + // Arrange + _mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any()) + .Returns(Result.Success(_userSettingsEntityFixture.Create(userId: _userId.Value, shouldAggregateMetadataWhenMissing: true))); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + _mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([artist]), Result>.Success([])); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist")); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == $"{PROVIDER_A_NAME}, {PROVIDER_B_NAME}"), + Arg.Any()); + } + + /// + /// Configures the provided substitute metadata provider so that it declares the artist lookup type for the music library type. + /// + /// The metadata provider substitute to configure. + /// The display name the provider reports. + private static void ConfigureProvider(IMetadataProvider metadataProvider, string name) + { + metadataProvider.Name.Returns(name); + metadataProvider.SupportedLibraryTypes.Returns(new List { LibraryType.Music }); + metadataProvider.RequiresWebAccess.Returns(false); + metadataProvider.LookupType.Returns(typeof(ArtistMetadataLookupDto)); + } + + /// + /// Creates an artist metadata that is usable and carries only a name, and optionally a set of genres. + /// + /// The name of the artist. + /// The optional genres of the artist. + /// The created artist metadata. + private ArtistMetadataDto CreateApplicableArtistMetadata(string name, List? genres = null) + { + return _artistMetadataDtoFixture.Create( + name: name, + genres: genres, + includeSortName: false, + includeDisambiguation: false, + includeType: false, + includeGender: false, + includeCountry: false, + includeArea: false, + includeBeginArea: false, + includeEndArea: false, + includeLifeSpanBegin: false, + includeLifeSpanEnd: false, + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeIpis: false, + includeIsnis: false, + includeGenres: genres is not null, + includeTags: false, + includeAliases: false, + includeRatings: false, + includeContributors: false); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs new file mode 100644 index 00000000..5051be57 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs @@ -0,0 +1,279 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMetadataExtractionJobTests +{ + private const string ROOT_PATH = @"C:\Music"; + private const string AUDIO_FILE_PATH = @"C:\Music\Queen\Bohemian Rhapsody.mp3"; + + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMusicLibraryScanItemMetadataRepository _mockMusicMetadataRepository; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; + private readonly ILibraryPathTemplateService _mockPathTemplateService; + private readonly IPathService _mockPathService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MusicMetadataExtractionJob _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + /// + /// Initializes a new instance of the class. + /// + public MusicMetadataExtractionJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository = Substitute.For(); + _mockMusicMetadataRepository = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicMetadataRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockPathTemplateService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + _mockServiceProvider.GetService(typeof(ILibraryPathTemplateService)).Returns(_mockPathTemplateService); + _mockServiceProvider.GetService(typeof(IPathService)).Returns(_mockPathService); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + // Default stubs that keep the happy path working, overridden per test where needed. + _mockMusicMetadataRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Created); + _mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(_libraryPathTemplateFixture.Create())); + _mockPathTemplateService.Parse(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.From>(Optional.None())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _sut = new MusicMetadataExtractionJob(_mockServiceScopeFactory, Substitute.For>()) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to retrieve the library")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockMusicMetadataRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenThereArePathsToProcess_ShouldStageTheirMetadataAndComplete() + { + // Arrange + SetupLibrary(); + SetupPaths(AUDIO_FILE_PATH); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockMusicMetadataRepository.Received(1).InsertRangeAsync( + Arg.Is>(items => items.Count == 1 + && items.First().Path == AUDIO_FILE_PATH + && items.First().LibraryScanId == _scanId.Value + && items.First().LibraryId == _libraryId.Value + && items.First().TrackTitle == "Bohemian Rhapsody"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThePathMatchesTheTemplate_ShouldApplyThePathDerivedMetadata() + { + // Arrange + SetupLibrary(); + SetupPaths(AUDIO_FILE_PATH); + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Queen", + [LibraryPathPartKind.ReleaseType] = "Album", + [LibraryPathPartKind.ReleaseYear] = "1975", + [LibraryPathPartKind.ReleaseName] = "A Night at the Opera", + [LibraryPathPartKind.TrackNumber] = "11", + [LibraryPathPartKind.DiscNumber] = "1", + [LibraryPathPartKind.TrackName] = "Bohemian Rhapsody" + }); + _mockPathTemplateService.Parse(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>(Optional.Some(parsedPath))); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockMusicMetadataRepository.Received(1).InsertRangeAsync( + Arg.Is>(items => items.Count == 1 + && items.First().ArtistName == "Queen" + && items.First().ReleaseType == MusicReleaseType.Album + && items.First().ReleaseYear == 1975 + && items.First().ReleaseName == "A Night at the Opera" + && items.First().TrackNumber == 11 + && items.First().DiscNumber == 1 + && items.First().TrackTitle == "Bohemian Rhapsody"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheStagingInsertFails_ShouldMarkJobAsFailed() + { + // Arrange + SetupLibrary(); + SetupPaths(AUDIO_FILE_PATH); + _mockMusicMetadataRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to stage the extracted metadata")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobIsCompleted_ShouldPublishProgressAndCallTheChildren() + { + // Arrange + SetupLibrary(); + SetupPaths(AUDIO_FILE_PATH); + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockDomainEventPublisher.Received().PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + /// + /// Stubs the media library reader with a library whose single content location is the test root path. + /// + private void SetupLibrary() + { + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + contentLocations: [ROOT_PATH]); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Stubs the staging results repository with the paths that need their metadata extracted. + /// + /// The file system paths that need their metadata extracted. + private void SetupPaths(params string[] paths) + { + _mockStagingResultsRepository.GetPathsNeedingRehashAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(paths)); + _mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns("Bohemian Rhapsody"); + _mockPathService.GetFileName(Arg.Any()).Returns("Bohemian Rhapsody.mp3"); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs index 5a2e3bc1..1bcd1732 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs @@ -1,18 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Security; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -23,17 +13,13 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; -using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -50,19 +36,14 @@ public class MediaLibraryScanArtworkEnrichmentJobTests private readonly IServiceScope _mockServiceScope; private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; - private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository; - private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaLibraryScanArtworkEnricher _mockArtworkEnricher; private readonly IDomainEventPublisher _mockDomainEventPublisher; - private readonly ILogger _mockLogger; private readonly MediaLibraryScanArtworkEnrichmentJob _sut; private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new(); - private readonly BookEntityFixture _bookEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); - private readonly ArtworkDtoFixture _artworkDtoFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; private readonly LibraryId _libraryId; @@ -79,23 +60,27 @@ public class MediaLibraryScanArtworkEnrichmentJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); - _mockArtworkConfigurationRepository = Substitute.For(); - _mockBookRepository = Substitute.For(); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository); - _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + // the job resolves the artwork enricher of the loaded library type from the service scope, so the music enricher must be available + _mockArtworkEnricher = Substitute.For(); + _mockArtworkEnricher.SupportedLibraryType.Returns(LibraryType.Music); + _mockArtworkEnricher.EnrichAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _mockServiceProvider.GetService(typeof(IEnumerable)) + .Returns(new IMediaLibraryScanArtworkEnricher[] { _mockArtworkEnricher }); + _mockDomainEventPublisher = Substitute.For(); _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) .Returns(ValueTask.CompletedTask); _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); - _mockLogger = Substitute.For>(); - _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); _libraryId = _libraryIdFixture.Create(); - _sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory, _mockLogger) + _sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory) { ScanId = _scanId, UserId = _userId, @@ -104,729 +89,39 @@ public class MediaLibraryScanArtworkEnrichmentJobTests } [Fact] - public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndTrackTheCoverArtworkAsEnriched() + public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent() { // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title"); - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - await mockBookArtworkService.Received(1).SaveBookArtworkAsync( - _libraryId.Value, - book.Id, - "My Library", - "Frank Herbert", - "Test Title", - Arg.Any(), - Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); - Assert.Equal(0, coverArtwork.Ordinal); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(123ul, coverArtwork.ContentHash); - Assert.Equal("Artwork Provider", coverArtwork.Provider); - Assert.NotNull(coverArtwork.LastUpdateUtc); + await _mockArtworkEnricher.Received(1).EnrichAsync(_libraryId, _scanId, _userId, Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } [Fact] - public async Task ExecuteAsync_WhenResolvedArtworkIsIdenticalToTheStoredOne_ShouldKeepTheStoredArtworkAndMarkItAsEnriched() + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - // the book already has a stored cover with the same content hash as the resolved artwork - book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the identical artwork is not copied again, so the artwork storage service is not called and the stored file name is kept - await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); - Assert.Equal("Artwork Provider", coverArtwork.Provider); - Assert.NotNull(coverArtwork.LastUpdateUtc); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenNoProviderReturnsArtwork_ShouldMarkTheCoverArtworkAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns((ArtworkDto?)null); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); - Assert.Equal(0, coverArtwork.Ordinal); - Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); - Assert.Null(coverArtwork.FileName); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichmentWithoutMarkingBooksAsFailed() - { - // Arrange - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a library without artwork providers must not mark its books as failed to resolve, so the books are not even queried - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() - { - // Arrange - using CancellationTokenSource cancellationTokenSource = new(); - cancellationTokenSource.Cancel(); - - // Act - Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); - - // Assert - await Assert.ThrowsAnyAsync(() => operation); - Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenReadingArtworkProviderConfigurationsFails_ShouldLogWarningAndSkipEnrichment() - { - // Arrange - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to read the artwork provider configurations")); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a failure to read the artwork configurations is best-effort, so the enrichment is skipped without touching the books - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenTheConfiguredArtworkProviderIsNotRegistered_ShouldLogWarningAndSkipEnrichment() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - - // the configuration references a plugin that is not registered in the dependency injection container - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1)])); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldSkipArtworkProvidersThatRequireWebAccess() - { - // Arrange - Guid webPluginId = Guid.NewGuid(); - Guid localPluginId = Guid.NewGuid(); - IArtworkProvider webProvider = Substitute.For(); - webProvider.Name.Returns("Web Provider"); - webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - webProvider.RequiresWebAccess.Returns(true); - IArtworkProvider localProvider = Substitute.For(); - localProvider.Name.Returns("Local Provider"); - localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - localProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/local-cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/local-cover.jpg").Returns(111UL); - - ServiceCollection services = new(); - services.AddKeyedSingleton(webPluginId, webProvider); - services.AddKeyedSingleton(localPluginId, localProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(mockBookArtworkService); - services.AddSingleton(mockFileHashService); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: false))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, webPluginId, 1), - _artworkConfigurationEntityFixture.Create(_libraryId.Value, localPluginId, 2) - ])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the provider that requires access to the web is skipped when the library does not permit web downloads - await webProvider.DidNotReceive().GetArtworkAsync(Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("Local Provider", coverArtwork.Provider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenCountingTheBooksNeedingArtworkFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to count the books that need artwork")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenGettingTheBooksNeedingArtworkFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the books that need artwork")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenGettingTheAuthorDisplayNamesFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the author display names")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenNoProviderReturnsArtworkAndTheBookHasAnExistingCover_ShouldMarkTheExistingCoverAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns((ArtworkDto?)null); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); - Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenStoringTheArtworkFailsAndTheBookHasNoExistingCover_ShouldTrackTheCoverAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Storage.Error", "Failed to store the artwork")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(111UL); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); - Assert.Null(coverArtwork.FileName); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenStoringTheArtworkFailsAndTheBookHasAnExistingCover_ShouldMarkTheExistingCoverAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Storage.Error", "Failed to store the artwork")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(222UL); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); - Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheResolvedArtworkIsRemote_ShouldComputeTheContentHashOfTheStoredArtwork() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.RequiresWebAccess.Returns(true); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash(Arg.Any()).Returns(999UL); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // for remote artwork, the content hash is computed on the stored copy, so it is only known after the artwork is stored - await mockBookArtworkService.Received(1).SaveBookArtworkAsync(_libraryId.Value, book.Id, "My Library", "Frank Herbert", Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(999ul, coverArtwork.ContentHash); - Assert.Equal("Artwork Provider", coverArtwork.Provider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheBookHasAnExistingCoverAndTheArtworkDiffersFromIt_ShouldStoreItAndUpdateTheExistingCover() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(222UL); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - // the book has no known ISBNs of its own, so the artwork lookup is built without an ISBN - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title", includeMetadata: false); - book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; - SetupSingleBookPage(book, artworkPluginId); - // the author of the book is not known, so its artwork directory falls back to an empty author name - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary())); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - await mockBookArtworkService.Received(1).SaveBookArtworkAsync( - _libraryId.Value, - book.Id, - "My Library", - string.Empty, - "Test Title", - Arg.Any(), - Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(222ul, coverArtwork.ContentHash); - Assert.Equal("Artwork Provider", coverArtwork.Provider); - Assert.NotNull(coverArtwork.LastUpdateUtc); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAnArtworkProviderThrows_ShouldTryTheNextProvider() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IArtworkProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new InvalidOperationException("The artwork provider failed"))); - IArtworkProvider secondProvider = Substitute.For(); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/second-cover.jpg").Returns(333UL); - - ServiceCollection services = new(); - services.AddKeyedSingleton(firstPluginId, firstProvider); - services.AddKeyedSingleton(secondPluginId, secondProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(mockBookArtworkService); - services.AddSingleton(mockFileHashService); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1), - _artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2) - ])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a failing artwork provider must not prevent the artwork of the other provider from being used - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("Second Provider", coverArtwork.Provider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAProviderReturnsRemoteArtworkWithoutRequiringWebAccess_ShouldSkipItAndUseTheNextProvider() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IArtworkProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.RequiresWebAccess.Returns(false); - firstProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg")); - IArtworkProvider secondProvider = Substitute.For(); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/second-cover.jpg").Returns(444UL); - - ServiceCollection services = new(); - services.AddKeyedSingleton(firstPluginId, firstProvider); - services.AddKeyedSingleton(secondPluginId, secondProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(mockBookArtworkService); - services.AddSingleton(mockFileHashService); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1), - _artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2) - ])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a provider that returns remote artwork must require web access, so its artwork is skipped and the next provider is used - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("Second Provider", coverArtwork.Provider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() - { - // Arrange - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - IMediaLibraryScanJob mockChildJob = Substitute.For(); - mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.CompletedTask); - _sut.AddChild(mockChildJob); - Guid id = Guid.NewGuid(); - object input = new(); - - // Act - await _sut.ExecuteAsync(id, input, CancellationToken.None); - - // Assert - await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - /// - /// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container. - /// - /// The Id of the plugin providing the artwork. - /// The artwork provider to resolve. - /// The service used to store the artwork of the books. - /// The service used to hash the artwork. - private void SetupRealServiceProvider(Guid artworkPluginId, IArtworkProvider artworkProvider, IBookArtworkService bookArtworkService, IFileHashService fileHashService) - { - ServiceCollection services = new(); - services.AddKeyedSingleton(artworkPluginId, artworkProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(bookArtworkService); - services.AddSingleton(fileHashService); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - } - - /// - /// Stubs the repositories so that the job processes a single page containing the given book, configured with the given artwork provider. - /// - /// The book whose artwork the job must resolve. - /// The Id of the plugin configured as artwork provider for the library. - private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId) - { - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1) - ])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + await _mockArtworkEnricher.DidNotReceive().EnrichAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs index d315fb11..b4fefe93 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -1,26 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.Fixtures.Core.DTO.Common; -using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; -using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -31,18 +13,13 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; -using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -59,21 +36,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests private readonly IServiceScope _mockServiceScope; private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; - private readonly IBookRepository _mockBookRepository; - private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaLibraryScanMetadataEnricher _mockMetadataEnricher; private readonly IDomainEventPublisher _mockDomainEventPublisher; - private readonly ILogger _mockLogger; private readonly MediaLibraryScanMetadataEnrichmentJob _sut; private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); - private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); - private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); - private readonly BookEntityFixture _bookEntityFixture = new(); - private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; @@ -91,25 +60,27 @@ public class MediaLibraryScanMetadataEnrichmentJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); - _mockConfigurationRepository = Substitute.For(); - _mockBookRepository = Substitute.For(); - _mockMediaContributorRepository = Substitute.For(); - _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); - _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + // The job resolves the metadata enricher of the loaded library type from the service scope, so the music enricher must be available. + _mockMetadataEnricher = Substitute.For(); + _mockMetadataEnricher.SupportedLibraryType.Returns(LibraryType.Music); + _mockMetadataEnricher.EnrichAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _mockServiceProvider.GetService(typeof(IEnumerable)) + .Returns(new IMediaLibraryScanMetadataEnricher[] { _mockMetadataEnricher }); + _mockDomainEventPublisher = Substitute.For(); _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) .Returns(ValueTask.CompletedTask); _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); - _mockLogger = Substitute.For>(); - _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); _libraryId = _libraryIdFixture.Create(); - _sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory, _mockLogger) + _sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory) { ScanId = _scanId, UserId = _userId, @@ -118,633 +89,39 @@ public class MediaLibraryScanMetadataEnrichmentJobTests } [Fact] - public async Task ExecuteAsync_WhenNoBooksNeedEnrichment_ShouldCompleteAndPublishFinishedEvent() + public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent() { // Arrange - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(0)); - _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipEnrichmentWithoutMarkingBooksAsFailed() - { - // Arrange - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a library without metadata providers must not mark its books as failed to enrich, so the book repositories are not touched - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenABookPageIsProcessed_ShouldDetachTheTrackedEntitiesAfterSaving() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the tracked entities of the page are detached after saving, so that the peak memory stays bounded regardless of the library size - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - _mockUnitOfWork.Received(1).ClearTrackedEntities(); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() - { - // Arrange - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the metadata provider configurations")); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + await _mockMetadataEnricher.Received(1).EnrichAsync(_libraryId, _scanId, _userId, Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() - { - // Arrange - using CancellationTokenSource cancellationTokenSource = new(); - cancellationTokenSource.Cancel(); - - // Act - Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); - - // Assert - await Assert.ThrowsAnyAsync(() => operation); - Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAggregateMetadataIsEnabled_ShouldFeedTheEarlierProvidersFindingsToTheLaterOnes() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - IMetadataProvider secondProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", openLibraryId: "OL123", description: "First Description")); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - // the book has no known identifiers of its own, so the findings of the first provider are fed to the second one - book.OpenLibraryId = null; - SetupSingleBookPage(book, firstPluginId, secondPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the second provider receives the lookup enriched with the open library Id discovered by the first provider - await secondProvider.Received(1).GetMetadataAsync( - Arg.Is(lookup => lookup is BookMetadataLookupDto && ((BookMetadataLookupDto)lookup).OpenLibraryId == "OL123"), - Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } [Fact] - public async Task ExecuteAsync_WhenAggregateMetadataIsDisabled_ShouldOnlyApplyTheFirstUsableProviderMetadata() + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - IMetadataProvider secondProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher")); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId, secondPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the second provider is not queried when the aggregation is disabled and the first provider returned usable metadata - await secondProvider.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookAsFailedToEnrich() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the enrichment state is tracked directly on the entity, so the failed status is visible on the same instance - Assert.Equal(MetadataStatus.Failed, book.MetadataStatus); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenMetadataIsEnriched_ShouldSetTheEnrichmentTrackingColumnsOnTheEntity() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the enrichment tracking columns are managed directly on the entity by the enrichment job - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal("First Provider", book.MetadataProvider); - Assert.NotNull(book.LastMetadataUpdateUtc); - Assert.Equal("First Title", book.Title); - Assert.Equal("First Publisher", book.Publisher); - } - - [Fact] - public async Task ExecuteAsync_WhenMetadataHasContributors_ShouldFindOrCreateThemAndLinkThemToTheBook() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); - MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", role: MediaContributorRole.Translator); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author, translator])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); - MediaContributorEntity translatorEntity = _mediaContributorEntityFixture.Create(displayName: "Jane Translator"); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) - .Returns(Result.From(authorEntity)); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any(), Arg.Any()) - .Returns(Result.From(translatorEntity)); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any(), Arg.Any()); - - // the participation rows are replaced on the entity, carrying the canonical role of each contributor - Assert.Equal(2, book.Contributors.Count); - BookContributorEntity linkedAuthor = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == authorEntity.Id); - Assert.Equal(MediaContributorRole.Author, linkedAuthor.Role); - Assert.Equal(book.Id, linkedAuthor.BookId); - BookContributorEntity linkedTranslator = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == translatorEntity.Id); - Assert.Equal(MediaContributorRole.Translator, linkedTranslator.Role); - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - } - - [Fact] - public async Task ExecuteAsync_WhenTheSameContributorAppearsInMultipleBooksOfAPage_ShouldFindOrCreateItOnlyOnce() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - - BookEntity firstBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/a.epub"); - BookEntity secondBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/b.epub"); - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(2)); - _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([firstBook, secondBook]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) - .Returns(Result.From(authorEntity)); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the contributor cache of the page guarantees a single contributor per person, so the repository is queried only once - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()); - Assert.Single(firstBook.Contributors); - Assert.Single(secondBook.Contributors); - Assert.Equal(authorEntity.Id, firstBook.Contributors[0].MediaContributorId); - Assert.Equal(authorEntity.Id, secondBook.Contributors[0].MediaContributorId); - } - - [Fact] - public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseMetadataProvidersThatRequireWebAccess() - { - // Arrange - Guid localPluginId = Guid.NewGuid(); - Guid webPluginId = Guid.NewGuid(); - IMetadataProvider localProvider = Substitute.For(); - localProvider.Name.Returns("Local Provider"); - localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - localProvider.RequiresWebAccess.Returns(false); - localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); - IMetadataProvider webProvider = Substitute.For(); - webProvider.Name.Returns("Web Provider"); - webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - webProvider.RequiresWebAccess.Returns(true); - webProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Web Title")); - - SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, localPluginId, webPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the local provider is used, but the provider requiring access to the web is skipped, so the book cannot be enriched - await localProvider.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); - await webProvider.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheLibraryPermitsWebDownloads_ShouldUseMetadataProvidersThatRequireWebAccess() - { - // Arrange - Guid localPluginId = Guid.NewGuid(); - Guid webPluginId = Guid.NewGuid(); - IMetadataProvider localProvider = Substitute.For(); - localProvider.Name.Returns("Local Provider"); - localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - localProvider.RequiresWebAccess.Returns(false); - localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); - IMetadataProvider webProvider = Substitute.For(); - webProvider.Name.Returns("Web Provider"); - webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - webProvider.RequiresWebAccess.Returns(true); - webProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Web Title")); - - SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, localPluginId, webPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the provider requiring access to the web is used when the library permits downloading data from the web - await webProvider.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenCountingTheBooksNeedingMetadataFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to count the books to enrich")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenGettingTheBooksPageNeedingMetadataFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the books to enrich")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileTryingTheProvidersInOrder_ShouldTryTheNextProvider() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new InvalidOperationException("The metadata provider failed"))); - IMetadataProvider secondProvider = Substitute.For(); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId, secondPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a failing metadata provider must not prevent the metadata of the next provider from being used - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal("Second Provider", book.MetadataProvider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileAggregatingMetadata_ShouldUseTheFindingsOfTheOtherProviders() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new InvalidOperationException("The metadata provider failed"))); - IMetadataProvider secondProvider = Substitute.For(); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId, secondPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal("Second Provider", book.MetadataProvider); - Assert.Equal("Second Title", book.Title); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAContributorHasNoDisplayName_ShouldSkipLinkingIt() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(role: MediaContributorRole.Author) with { Name = null }; - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [namelessContributor])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a contributor without a display name cannot be linked to the book, so no contributor is queried or created - await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); - Assert.Empty(book.Contributors); - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAContributorHasNoRole_ShouldLinkItWithTheDefaultRole() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto contributorWithoutRole = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert") with { Role = null }; - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [contributorWithoutRole])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", includeMetadata: false); - SetupSingleBookPage(book, firstPluginId); - - MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) - .Returns(Result.From(authorEntity)); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a contributor without a role is linked with the default canonical role - BookContributorEntity linkedContributor = Assert.Single(book.Contributors); - Assert.Equal(MediaContributorRole.Author, linkedContributor.Role); - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenFindingOrCreatingAContributorFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to find or create the contributor")); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() - { - // Arrange - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - IMediaLibraryScanJob mockChildJob = Substitute.For(); - mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.CompletedTask); - _sut.AddChild(mockChildJob); - Guid id = Guid.NewGuid(); - object input = new(); - - // Act - await _sut.ExecuteAsync(id, input, CancellationToken.None); - - // Assert - await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - /// - /// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container. - /// - /// The Id of the plugin providing the first metadata provider. - /// The first metadata provider to resolve. - /// The Id of the plugin providing the second metadata provider, if any. - /// The second metadata provider to resolve, if any. - /// Whether the user settings enable aggregating metadata from multiple providers when fields are missing. - private void SetupRealServiceProviderForProviders(Guid firstPluginId, IMetadataProvider firstProvider, Guid? secondPluginId = null, IMetadataProvider? secondProvider = null, bool shouldAggregateMetadataWhenMissing = false) - { - ServiceCollection services = new(); - services.AddKeyedSingleton(firstPluginId, firstProvider); - if (secondPluginId is not null && secondProvider is not null) - services.AddKeyedSingleton(secondPluginId.Value, secondProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); - mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing))); - _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); - } - - /// - /// Stubs the repositories so that the job processes a single page containing the given book, configured with the given metadata providers. - /// - /// The book the job must enrich. - /// The Ids of the plugins configured as metadata providers for the library. - private void SetupSingleBookPage(BookEntity book, params Guid[] configuredPluginIds) - { - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>( - configuredPluginIds.Select((pluginId, index) => _configurationEntityFixture.Create(_libraryId.Value, pluginId, index + 1)).ToList())); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + await _mockMetadataEnricher.DidNotReceive().EnrichAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs index 84ef1735..d702d563 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs @@ -12,9 +12,11 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -22,6 +24,7 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContex using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; @@ -55,8 +58,8 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; @@ -83,6 +86,9 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + // The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available. + _mockServiceProvider.GetService(typeof(IEnumerable)) + .Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(Substitute.For(), Substitute.For()) }); _mockDomainEventPublisher = Substitute.For(); _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) @@ -113,7 +119,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // a missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted + // A missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted. await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -121,6 +127,24 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } + [Fact] + public async Task ExecuteAsync_WhenFingerprintsArePersisted_ShouldPublishProgressChangedEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + [Fact] public async Task ExecuteAsync_WhenMetadataFingerprintDiffers_ShouldResetTheMetadataStatus() { @@ -134,7 +158,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job + // The metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job. await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()); await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -155,7 +179,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job + // The artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job. await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()); await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -168,13 +192,13 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests { // Arrange LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); - List metadataConfigurations = _metadataConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1); - List artworkConfigurations = _artworkConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1); + List metadataConfigurations = _libraryMetadataProviderConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1); + List artworkConfigurations = _libraryArtworkProviderConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1); SetupLibraryAndConfigurations(library, metadataConfigurations, artworkConfigurations); - // the stored fingerprints match the ones computed from the current provider configuration + // The stored fingerprints match the ones computed from the current provider configuration. string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(metadataConfigurations, false, library.CanDownloadMetadataFromWeb); - string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, library.CanDownloadMetadataFromWeb); + string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, false, library.CanDownloadMetadataFromWeb); library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; @@ -182,7 +206,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted + // The configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted. await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -194,7 +218,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests public async Task ExecuteAsync_WhenBothFingerprintsDiffer_ShouldPersistTheUpdatedFingerprintsViaSaveChangesOnly() { // Arrange - // both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity + // Both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity. LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: "STALE_ARTWORK"); SetupLibraryAndConfigurations(library); _mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()) @@ -206,8 +230,8 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and - // flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run + // Regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and + // flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run. await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()); await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -359,7 +383,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted + // Reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted. Assert.NotNull(library.MetadataProvidersConfigurationFingerprint); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -377,7 +401,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the user settings repository is optional, its absence must not prevent the fingerprints from being persisted + // The user settings repository is optional, its absence must not prevent the fingerprints from being persisted. Assert.NotNull(library.MetadataProvidersConfigurationFingerprint); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -413,6 +437,8 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests /// The artwork provider configurations of the media library. private void SetupLibraryAndConfigurations(LibraryEntity library, List? metadataConfigurations = null, List? artworkConfigurations = null) { + // The job resolves the materializer by the library type, so the fixture-provided library must be of the type the books materializer supports. + library.LibraryType = LibraryType.Book; _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); SetupConfigurations(metadataConfigurations, artworkConfigurations); @@ -429,14 +455,14 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>( metadataConfigurations ?? [ - _metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1), - _metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2) + _libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1), + _libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2) ])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>( artworkConfigurations ?? [ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1), - _artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2) + _libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1), + _libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2) ])); IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs index ccc0f5ee..19c71a21 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs @@ -1,22 +1,27 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using System; @@ -39,6 +44,7 @@ public class MediaLibraryScanResultsSaveJobTests private readonly IServiceScope _mockServiceScope; private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository; private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; private readonly IBookRepository _mockBookRepository; @@ -47,6 +53,7 @@ public class MediaLibraryScanResultsSaveJobTests private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; @@ -64,13 +71,31 @@ public class MediaLibraryScanResultsSaveJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); _mockSnapshotRepository = Substitute.For(); _mockStagingResultsRepository = Substitute.For(); _mockBookRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository); _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + // By default no book exists yet, so every scanned path is materialized; the tests that need existing books override this. + _mockBookRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + // The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available. + ILibraryPathTemplateService mockPathTemplateService = Substitute.For(); + mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty())); + IPathService mockPathService = Substitute.For(); + mockPathService.GetFileName(Arg.Any()).Returns(callInfo => callInfo.Arg()); + mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns(callInfo => + { + string fileName = callInfo.Arg(); + int lastDotIndex = fileName.LastIndexOf('.'); + return lastDotIndex <= 0 ? fileName : fileName[..lastDotIndex]; + }); + _mockServiceProvider.GetService(typeof(IEnumerable)) + .Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, mockPathService) }); _mockDomainEventPublisher = Substitute.For(); _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) @@ -80,6 +105,8 @@ public class MediaLibraryScanResultsSaveJobTests _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); _libraryId = _libraryIdFixture.Create(); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Book))); _sut = new MediaLibraryScanResultsSaveJob(_mockServiceScopeFactory) { ScanId = _scanId, @@ -102,8 +129,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["book1.pdf", "book2.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) - .Returns(Result.From(null)); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Created)); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); @@ -121,6 +148,31 @@ public class MediaLibraryScanResultsSaveJobTests await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); } + [Fact] + public async Task ExecuteAsync_WhenScanResultsAreApplied_ShouldPublishProgressChangedEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + [Fact] public async Task ExecuteAsync_WhenNoContentChanged_ShouldNotResetTheEnrichmentState() { @@ -139,7 +191,7 @@ public class MediaLibraryScanResultsSaveJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // no book content changed since the last scan, so the enrichment state of the books must not be reset + // No book content changed since the last scan, so the enrichment state of the books must not be reset. await _mockBookRepository.DidNotReceive().ResetEnrichmentStateForPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } @@ -156,8 +208,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["existing.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, "existing.pdf", Arg.Any()) - .Returns(Result.From(_bookEntityFixture.Create(path: "existing.pdf"))); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From>(["existing.pdf"])); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act @@ -292,7 +344,7 @@ public class MediaLibraryScanResultsSaveJobTests } [Fact] - public async Task ExecuteAsync_WhenGettingExistingBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + public async Task ExecuteAsync_WhenGettingExistingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) @@ -303,8 +355,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["book1.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the existing book")); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the existing paths")); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -329,8 +381,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["book1.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) - .Returns(Result.From(null)); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to insert the shell book")); @@ -385,8 +437,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["_.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, "_.pdf", Arg.Any()) - .Returns(Result.From(null)); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Created)); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); @@ -395,7 +447,7 @@ public class MediaLibraryScanResultsSaveJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback + // The file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback. await _mockBookRepository.Received(1).InsertAsync(Arg.Is(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprintTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprintTests.cs new file mode 100644 index 00000000..8e2fc93b --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprintTests.cs @@ -0,0 +1,198 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ProviderConfigurationFingerprintTests +{ + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new(); + + [Fact] + public void ComputeMetadataFingerprint_WhenCalledWithTheSameConfiguration_ShouldReturnTheSameFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List configurations = + [ + _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0), + _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1) + ]; + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true); + string secondFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true); + + // Assert + Assert.Equal(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputeMetadataFingerprint_WhenOnlyTheOrderOfConfigurationsDiffers_ShouldReturnTheSameFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity first = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0); + LibraryMetadataProviderConfigurationEntity second = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1); + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([first, second], false, true); + string secondFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([second, first], false, true); + + // Assert + Assert.Equal(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputeMetadataFingerprint_WhenAProviderChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity enabled = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, rank: 0, isEnabled: true); + LibraryMetadataProviderConfigurationEntity disabled = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, rank: 0, isEnabled: false); + + // Act + string enabledFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([enabled], false, true); + string disabledFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([disabled], false, true); + + // Assert + Assert.NotEqual(enabledFingerprint, disabledFingerprint); + } + + [Fact] + public void ComputeMetadataFingerprint_WhenTheAggregationSettingChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List configurations = [_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)]; + + // Act + string withoutAggregation = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true); + string withAggregation = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, true, true); + + // Assert + Assert.NotEqual(withoutAggregation, withAggregation); + } + + [Fact] + public void ComputeMetadataFingerprint_WhenTheWebAccessSettingChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List configurations = [_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)]; + + // Act + string withoutWebAccess = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, false); + string withWebAccess = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true); + + // Assert + Assert.NotEqual(withoutWebAccess, withWebAccess); + } + + [Fact] + public void ComputeArtworkFingerprint_WhenOnlyTheOrderOfConfigurationsDiffers_ShouldReturnTheSameFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity first = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0); + LibraryArtworkProviderConfigurationEntity second = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1); + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([first, second], false, true); + string secondFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([second, first], false, true); + + // Assert + Assert.Equal(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputeArtworkFingerprint_WhenAProviderChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity first = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0); + LibraryArtworkProviderConfigurationEntity second = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0); + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([first], false, true); + string secondFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([second], false, true); + + // Assert + Assert.NotEqual(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputeArtworkFingerprint_WhenTheAggregationSettingChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List configurations = [_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)]; + + // Act + string withoutAggregation = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(configurations, false, true); + string withAggregation = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(configurations, true, true); + + // Assert + Assert.NotEqual(withoutAggregation, withAggregation); + } + + [Fact] + public void ComputePathTemplateFingerprint_WhenOnlyTheOrderOfPartsDiffers_ShouldReturnTheSameFingerprint() + { + // Arrange + LibraryPathTemplatePartEntity first = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}"); + LibraryPathTemplatePartEntity second = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.ReleaseName, representation: "{0}"); + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([first, second]); + string secondFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([second, first]); + + // Assert + Assert.Equal(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputePathTemplateFingerprint_WhenAPartChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + LibraryPathTemplatePartEntity artist = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}"); + LibraryPathTemplatePartEntity releaseName = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.ReleaseName, representation: "{0}"); + + // Act + string artistFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([artist]); + string releaseNameFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([releaseName]); + + // Assert + Assert.NotEqual(artistFingerprint, releaseNameFingerprint); + } + + [Fact] + public void ComputePathTemplateFingerprint_WhenTheOptionalityChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + LibraryPathTemplatePartEntity required = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity optional = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true); + + // Act + string requiredFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([required]); + string optionalFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([optional]); + + // Assert + Assert.NotEqual(requiredFingerprint, optionalFingerprint); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricherTests.cs new file mode 100644 index 00000000..a397e4fa --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricherTests.cs @@ -0,0 +1,482 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksMediaLibraryScanArtworkEnricherTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository; + private readonly IBookRepository _mockBookRepository; + private readonly IArtworkProvider _mockArtworkProvider; + private readonly IBookArtworkService _mockBookArtworkService; + private readonly IFileHashService _mockFileHashService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ILogger _mockLogger; + private readonly BooksMediaLibraryScanArtworkEnricher _sut; + private readonly ServiceProvider _serviceProvider; + private readonly Guid _pluginId = Guid.NewGuid(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BooksMediaLibraryScanArtworkEnricherTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockArtworkProviderConfigurationRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + _mockArtworkProvider = Substitute.For(); + _mockArtworkProvider.Name.Returns("Test Provider"); + _mockArtworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + _mockArtworkProvider.RequiresWebAccess.Returns(true); + + _mockBookArtworkService = Substitute.For(); + _mockFileHashService = Substitute.For(); + _mockFileHashService.ComputeFileHash(Arg.Any()).Returns(123UL); + _mockDomainEventPublisher = Substitute.For(); + _mockLogger = Substitute.For>(); + + // The enricher resolves the keyed artwork providers from the scope of the service provider, so a real container is used to honor the keyed registration. + ServiceCollection services = new(); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(_mockBookArtworkService); + services.AddSingleton(_mockFileHashService); + services.AddKeyedSingleton(_pluginId, _mockArtworkProvider); + _serviceProvider = services.BuildServiceProvider(); + _sut = new BooksMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService(), _mockLogger); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + } + + [Fact] + public void SupportedLibraryType_WhenCalled_ShouldReturnBook() + { + // Act + LibraryType result = _sut.SupportedLibraryType; + + // Assert + Assert.Equal(LibraryType.Book, result); + } + + [Fact] + public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment() + { + // Arrange + SetupLibrary(); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment() + { + // Arrange + SetupLibrary(); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Provider.Error", "Failed to read the configurations")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess() + { + // Arrange + SetupLibrary(canDownloadMetadataFromWeb: false); + SetupConfiguration(); + _mockArtworkProvider.RequiresWebAccess.Returns(true); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve() + { + // Arrange + SetupLibrary(canDownloadMetadataFromWeb: false); + SetupConfiguration(); + _mockArtworkProvider.RequiresWebAccess.Returns(false); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockArtworkProvider.Received(1).GetArtworkAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheBookHasArtwork_ShouldStoreAndPersistEnrichedArtwork() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg", type: ArtworkType.Cover, ordinal: 0)])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookArtworkService.Received(1).SaveBookArtworkAsync( + book.LibraryId, + book.Id, + Arg.Any(), + Arg.Any(), + book.Title, + Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), + Arg.Any()); + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkType.Cover, artwork.ArtworkType); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(ArtworkStatus.Enriched, artwork.Status); + Assert.Equal("Test Provider", artwork.Provider); + Assert.Equal("/media/books/cover.jpg", artwork.FileName); + Assert.Equal(123UL, artwork.ContentHash); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenAProviderAnswersWithNoArtwork_ShouldMarkTheBookFailed() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Failed, artwork.Status); + Assert.Null(artwork.FileName); + Assert.Null(artwork.Provider); + } + + [Fact] + public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheBookFailed() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException>(new HttpRequestException("Transient failure."))); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Failed, artwork.Status); + } + + [Fact] + public async Task EnrichAsync_WhenTheProviderReturnsRemoteArtworkButDoesNotRequireWebAccess_ShouldMarkTheBookFailed() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + _mockArtworkProvider.RequiresWebAccess.Returns(false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Failed, artwork.Status); + } + + [Fact] + public async Task EnrichAsync_WhenTheStoredArtworkIsIdentical_ShouldKeepItAndMarkItEnriched() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + _mockArtworkProvider.RequiresWebAccess.Returns(false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + BookArtworkEntity existingArtwork = _bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, contentHash: 123UL, status: ArtworkStatus.Enriched); + book.Artwork = [existingArtwork]; + SetupBooks(book); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: "/media/books/local.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Enriched, artwork.Status); + Assert.Equal("Test Provider", artwork.Provider); + } + + [Fact] + public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheBookFailed() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.Error", "Failed to store the artwork")); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Failed, artwork.Status); + } + + [Fact] + public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to count the books")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the books")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheAuthorsCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book])); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the authors")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to save the changes")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + SetupLibrary(); + SetupConfiguration(); + SetupBooks(); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + /// + /// Stubs the media library reader with a library owned by the test user. + /// + /// Whether the library allows downloading data from the web. + private void SetupLibrary(bool canDownloadMetadataFromWeb = true) + { + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Book, + canDownloadMetadataFromWeb: canDownloadMetadataFromWeb); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Stubs the artwork provider configuration reader with a single enabled configuration for the test plugin. + /// + private void SetupConfiguration() + { + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _pluginId, 0)])); + } + + /// + /// Stubs the book reader with a single page holding the provided books. + /// + /// The books of the page. + private void SetupBooks(params BookEntity[] books) + { + _mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(books.Length)); + _mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(books), + Result.From>([])); + Dictionary authors = books.ToDictionary(book => book.Id, book => (string?)"Frank Herbert"); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(authors)); + } + + /// + /// Stubs the artwork storage so that a book stores its artwork successfully. + /// + private void SetupSuccessStore() + { + _mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/books/cover.jpg")); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs new file mode 100644 index 00000000..6e7cfab0 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksMediaLibraryScanItemMaterializerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryPathTemplateService _mockPathTemplateService; + private readonly IPathService _mockPathService; + private readonly BooksMediaLibraryScanItemMaterializer _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly Guid _libraryId; + private readonly Guid _scanId; + + /// + /// Initializes a new instance of the class. + /// + public BooksMediaLibraryScanItemMaterializerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockPathTemplateService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _libraryId = Guid.NewGuid(); + _scanId = Guid.NewGuid(); + + // Default stubs: the library has no path template of its own, no book is stored yet, and the separator is the Windows one. + _mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()) + .Returns(Result.From(LibraryPathTemplate.Empty())); + _mockPathService.PathSeparator.Returns('\\'); + _mockPathService.GetFileNameWithoutExtension(Arg.Any()).Returns("track"); + _mockBookRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Created)); + _mockPathTemplateService.Parse(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(Optional.None())); + + _sut = new BooksMediaLibraryScanItemMaterializer(_mockPathTemplateService, _mockPathService); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenPathSharesTheContentLocationPrefixButIsOutside_ShouldFallBackToTheFileNameRelativePath() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]); + _mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockPathService.IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music").Returns(false); + _mockPathService.GetFileName("C:\\MusicBackup\\track.epub").Returns("track.epub"); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\MusicBackup\\track.epub"], CancellationToken.None); + + // Assert + // A sibling directory whose name only starts with the content location name is not inside the library, so the item is not parsed against + // the path template, and the file name is used as the relative path instead. + Assert.False(result.IsFailure); + _mockPathService.Received(1).IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music"); + _mockPathTemplateService.Received(1).Parse(Arg.Any(), Arg.Any(), "track.epub", '\\'); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenPathIsInsideTheContentLocation_ShouldParseThePathRelativeToTheContentLocation() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]); + _mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockPathService.IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music").Returns(true); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\Music\\Artist\\track.epub"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockPathService.Received(1).IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music"); + _mockPathTemplateService.Received(1).Parse(Arg.Any(), Arg.Any(), "Artist\\track.epub", '\\'); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricherTests.cs new file mode 100644 index 00000000..8de68542 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricherTests.cs @@ -0,0 +1,383 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksMediaLibraryScanMetadataEnricherTests +{ + private const string PROVIDER_A_NAME = "ProviderA"; + private const string PROVIDER_B_NAME = "ProviderB"; + + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IMetadataProvider _mockProviderA; + private readonly IMetadataProvider _mockProviderB; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ServiceProvider _serviceProvider; + private readonly BooksMediaLibraryScanMetadataEnricher _sut; + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public BooksMediaLibraryScanMetadataEnricherTests() + { + _mockUnitOfWork = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockMetadataConfigurationRepository = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository); + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + + _mockProviderA = Substitute.For(); + ConfigureProvider(_mockProviderA, PROVIDER_A_NAME); + _mockProviderB = Substitute.For(); + ConfigureProvider(_mockProviderB, PROVIDER_B_NAME); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + + // The configured providers are registered under the plugin Ids they are configured with, the way the host registers plugin provided services. + Guid pluginAId = Guid.NewGuid(); + Guid pluginBId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result>.Success( + [ + _libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginAId, rank: 1), + _libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginBId, rank: 2) + ])); + + ServiceCollection services = new(); + services.AddScoped(_ => _mockUnitOfWork); + services.AddScoped(_ => _mockDomainEventPublisher); + services.AddKeyedTransient(pluginAId, (serviceProvider, serviceKey) => _mockProviderA); + services.AddKeyedTransient(pluginBId, (serviceProvider, serviceKey) => _mockProviderB); + _serviceProvider = services.BuildServiceProvider(); + + _sut = new BooksMediaLibraryScanMetadataEnricher(_serviceProvider.GetRequiredService(), NullLogger.Instance); + + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(1)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([])); + _mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any()) + .Returns(Result.Success(null)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.From(Result.Success)); + } + + [Fact] + public async Task EnrichAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipTheEnrichment() + { + // Arrange + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result>.Success([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheMetadataConfigurationsCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Provider.Error", "Failed to read the configurations")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheFirstProviderReturnsApplicableMetadata_ShouldNotQueryTheFollowingProviders() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal(PROVIDER_A_NAME, book.MetadataProvider); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheFirstProviderReturnsNoUsableMetadata_ShouldQueryTheFollowingProviders() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)null); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal(PROVIDER_B_NAME, book.MetadataProvider); + } + + [Fact] + public async Task EnrichAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookFailed() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)null); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)null); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + Assert.Equal(MetadataStatus.Failed, book.MetadataStatus); + } + + [Fact] + public async Task EnrichAsync_WhenAggregationIsEnabled_ShouldQueryEveryProviderAndMergeTheirMetadata() + { + // Arrange + _mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any()) + .Returns(Result.Success(_userSettingsEntityFixture.Create(userId: _userId.Value, shouldAggregateMetadataWhenMissing: true))); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune")); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune Messiah")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal($"{PROVIDER_A_NAME}, {PROVIDER_B_NAME}", book.MetadataProvider); + } + + [Fact] + public async Task EnrichAsync_WhenTheMetadataHasContributors_ShouldLinkThemToTheBook() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(contributor)); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata( + "Dune", + contributors: [_mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author, legalName: null)])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", null, Arg.Any()); + BookContributorEntity linkedContributor = Assert.Single(book.Contributors); + Assert.Equal(contributor.Id, linkedContributor.MediaContributorId); + Assert.Equal(MediaContributorRole.Author, linkedContributor.Role); + } + + [Fact] + public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to count the books")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the books")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to save the changes")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + /// + /// Stubs the book reader with a single page holding the provided books. + /// + /// The books of the page. + private void SetupBooks(params BookEntity[] books) + { + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(books.Length)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result>.Success(books), + Result>.Success([])); + } + + /// + /// Configures the provided substitute metadata provider so that it declares the book lookup type for the books media library type. + /// + /// The metadata provider substitute to configure. + /// The display name the provider reports. + private static void ConfigureProvider(IMetadataProvider metadataProvider, string name) + { + metadataProvider.Name.Returns(name); + metadataProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + metadataProvider.RequiresWebAccess.Returns(false); + metadataProvider.LookupType.Returns(typeof(BookMetadataLookupDto)); + } + + /// + /// Creates a book metadata that is usable and carries only a title, and optionally a set of contributors. + /// + /// The title of the book. + /// The optional contributors of the book. + /// The created book metadata. + private BookMetadataDto CreateApplicableBookMetadata(string title, List? contributors = null) + { + return _bookMetadataDtoFixture.Create( + title: title, + contributors: contributors); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 2c2f28fd..7edeb01f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -144,7 +144,7 @@ public class BookArtworkServiceTests string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); - FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json")); _mockFileProviderService.GetFilePaths(Arg.Any(), true) .Returns(Result.From>([coverFileId, otherFileId])); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs index 9b3069b6..e2581ec0 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs @@ -41,7 +41,7 @@ public class BookReadingServiceTests private readonly Guid _bookId = Guid.NewGuid(); private readonly Guid _libraryId = Guid.NewGuid(); private readonly string _bookPath; - private readonly LibraryBookReaderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -61,7 +61,7 @@ public class BookReadingServiceTests _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository); - LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true); + LibraryBookReaderConfigurationEntity enabledConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true); _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any()) .Returns(Result.From(enabledConfiguration)); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs index 6f31de34..762ff669 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -35,9 +35,9 @@ public class MediaLibraryProviderConfigurationStoreTests private readonly ILibraryBookReaderConfigurationRepository _mockBookReaderConfigurationRepository; private readonly IPluginManager _mockPluginManager; private readonly IBookReaderEnablementCache _mockEnablementCache; - private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationFixture = new(); - private readonly LibraryBookReaderConfigurationEntityFixture _bookReaderConfigurationFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -62,7 +62,7 @@ public class MediaLibraryProviderConfigurationStoreTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity configuration = _metadataConfigurationFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configuration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([configuration])); MediaLibraryProviderConfigurationStore sut = CreateSut(); @@ -122,7 +122,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); - LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 4); + LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, 4); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); @@ -185,7 +185,7 @@ public class MediaLibraryProviderConfigurationStoreTests MediaLibraryProviderConfigurationStore sut = CreateSut( (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), (betaPluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); - LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, alphaPluginId, 1); + LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) @@ -371,7 +371,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); - LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: pluginId); + LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); @@ -473,7 +473,7 @@ public class MediaLibraryProviderConfigurationStoreTests MediaLibraryProviderConfigurationStore sut = CreateSut( (alphaPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf")), (betaPluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); - LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: alphaPluginId); + LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: alphaPluginId); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) @@ -524,7 +524,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); - LibraryBookReaderConfigurationEntity staleConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: stalePluginId); + LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([staleConfiguration])); _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) @@ -641,7 +641,7 @@ public class MediaLibraryProviderConfigurationStoreTests MediaLibraryProviderConfigurationStore sut = CreateSut( (alphaPluginId, null, CreateArtworkProvider(LibraryType.Book), null), (betaPluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); - LibraryArtworkProviderConfigurationEntity existingArtworkConfiguration = _artworkConfigurationFixture.Create(libraryId, alphaPluginId, 1); + LibraryArtworkProviderConfigurationEntity existingArtworkConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) @@ -674,7 +674,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha"); _mockPluginManager.GetPlugins().Returns([alphaPlugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((alphaPluginId, null, CreateArtworkProvider(LibraryType.Movie), null)); - LibraryArtworkProviderConfigurationEntity staleArtworkConfiguration = _artworkConfigurationFixture.Create(libraryId, alphaPluginId, 1); + LibraryArtworkProviderConfigurationEntity staleArtworkConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) @@ -698,7 +698,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null)); - LibraryArtworkProviderConfigurationEntity existingConfiguration = _artworkConfigurationFixture.Create(libraryId, pluginId, 3); + LibraryArtworkProviderConfigurationEntity existingConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, pluginId, 3); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) @@ -788,7 +788,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); - LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 1); + LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, 1); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) @@ -814,7 +814,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); - LibraryArtworkProviderConfigurationEntity existingConfiguration = _artworkConfigurationFixture.Create(libraryId, pluginId, 1); + LibraryArtworkProviderConfigurationEntity existingConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, pluginId, 1); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) @@ -861,7 +861,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); - LibraryMetadataProviderConfigurationEntity staleConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 1); + LibraryMetadataProviderConfigurationEntity staleConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, 1); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([staleConfiguration])); _mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) @@ -951,7 +951,7 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); - LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: pluginId); + LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index ffb41c8d..6e124e1c 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -9,6 +9,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; @@ -51,6 +52,8 @@ public class PluginDetectionSyncJobTests private readonly PluginLoadErrorDtoFixture _pluginLoadErrorDtoFixture; private readonly PluginEntityFixture _pluginEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly PaginatedResultDtoFixture _pluginPaginatedResultDtoFixture = new(); + private readonly PaginatedResultDtoFixture _libraryPaginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -191,7 +194,7 @@ public class PluginDetectionSyncJobTests PluginEntity loadedPluginRow = _pluginEntityFixture.Create(id: loadedPlugin.Id, name: loadedPlugin.Name, loadStatus: PluginLoadStatus.Loaded); PluginEntity stalePluginRow = _pluginEntityFixture.Create(name: "Stale Plugin", loadStatus: PluginLoadStatus.Loaded); _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [loadedPluginRow, stalePluginRow], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + .Returns(Result.From(_pluginPaginatedResultDtoFixture.Create(data: [loadedPluginRow, stalePluginRow], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockPluginRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Deleted); PluginDetectionSyncJob sut = CreateSut(); @@ -217,7 +220,7 @@ public class PluginDetectionSyncJobTests .Returns(Result.From(Result.Updated)); LibraryEntity bookLibrary = _libraryEntityFixture.Create(libraryType: LibraryType.Book); _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [bookLibrary], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + .Returns(Result.From(_libraryPaginatedResultDtoFixture.Create(data: [bookLibrary], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); PluginDetectionSyncJob sut = CreateSut(); @@ -244,7 +247,7 @@ public class PluginDetectionSyncJobTests errorMessage: "Failed to load plugin assembly 'MyPlugin.dll': unexpected error"); PluginEntity staleLoadedRow = _pluginEntityFixture.Create(id: previouslyLoadedPlugin.Id, name: previouslyLoadedPlugin.Name, loadStatus: PluginLoadStatus.Loaded); _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) - .Returns(Result.From(new PaginatedResultDto { Data = [staleLoadedRow], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + .Returns(Result.From(_pluginPaginatedResultDtoFixture.Create(data: [staleLoadedRow], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockPluginRepository.DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any()) .Returns(Result.Deleted); PluginDetectionSyncJob sut = CreateSut([loadError]); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs index 5855411a..a494cee3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs @@ -9,6 +9,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; @@ -56,6 +57,8 @@ public class ScheduledJobSchedulerJobTests private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); private readonly ScheduledJobFixture _scheduledJobFixture = new(); private readonly IntervalScheduleFixture _intervalScheduleFixture = new(); + private readonly PaginatedResultDtoFixture _themePaginatedResultDtoFixture = new(); + private readonly PaginatedResultDtoFixture _scheduledJobPaginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -342,7 +345,7 @@ public class ScheduledJobSchedulerJobTests IThemeService mockThemeService = Substitute.For(); mockThemeService.GetBundledThemeArchivePaths().Returns([]); IThemeRepository mockThemeRepository = Substitute.For(); - mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_themePaginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); _services[typeof(IThemeService)] = mockThemeService; @@ -390,10 +393,12 @@ public class ScheduledJobSchedulerJobTests { // Arrange _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(Array.Empty()); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_scheduledJobPaginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); IThemeService mockThemeService = Substitute.For(); mockThemeService.GetBundledThemeArchivePaths().Returns([]); IThemeRepository mockThemeRepository = Substitute.For(); - mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_themePaginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); _services[typeof(IThemeService)] = mockThemeService; using CancellationTokenSource cancellationTokenSource = new(); @@ -407,6 +412,61 @@ public class ScheduledJobSchedulerJobTests await _mockScheduledJobRepository.Received(2).GetActiveOrRunningAsync(Arg.Any()); } + [Fact] + public async Task EnsureTechnicalDataCleanupScheduledJobAsync_WhenTheJobAlreadyExists_ShouldNotInsertIt() + { + // Arrange + ScheduledJobEntity existingJob = _scheduledJobEntityFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup, status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_scheduledJobPaginatedResultDtoFixture.Create(data: [existingJob], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + + // Act + await InvokeAsync("EnsureTechnicalDataCleanupScheduledJobAsync", CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureTechnicalDataCleanupScheduledJobAsync_WhenThereAreNoScheduledJobs_ShouldNotInsertIt() + { + // Arrange + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_scheduledJobPaginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); + + // Act + await InvokeAsync("EnsureTechnicalDataCleanupScheduledJobAsync", CancellationToken.None); + + // Assert + // A fresh installation seeds the default jobs, including the technical data cleanup one, during the application setup. + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureTechnicalDataCleanupScheduledJobAsync_WhenTheJobIsMissing_ShouldInsertItOwnedByTheOtherJobsOwner() + { + // Arrange + Guid ownerUserId = Guid.NewGuid(); + ScheduledJobEntity existingJob = _scheduledJobEntityFixture.Create(taskType: ScheduledTaskType.RepairThemes, status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup, ownerUserId: ownerUserId); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_scheduledJobPaginatedResultDtoFixture.Create(data: [existingJob], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + + // Act + await InvokeAsync("EnsureTechnicalDataCleanupScheduledJobAsync", CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.Received(1).InsertAsync( + Arg.Is(scheduledJob => + scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && + scheduledJob.ScheduleType == ScheduleType.OnceAtStartup && + scheduledJob.Status == ScheduledJobStatus.Active && + scheduledJob.OwnerUserId == ownerUserId && + scheduledJob.CreatedBy == ownerUserId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task RunCycleWorkerAsync_WhenTheScheduleCannotBeLoaded_ShouldEndTheCycle() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs index 075bace8..a7dcef91 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs @@ -24,6 +24,7 @@ public class ScheduledTaskExecutorFactoryTests private readonly TemporaryFilesCleanupTaskExecutor _mockTemporaryFilesCleanupTaskExecutor; private readonly RepairThemesTaskExecutor _mockRepairThemesTaskExecutor; private readonly CleanScheduledJobExecutionHistoryTaskExecutor _mockCleanScheduledJobExecutionHistoryTaskExecutor; + private readonly TechnicalDataCleanupTaskExecutor _mockTechnicalDataCleanupTaskExecutor; private readonly ScheduledTaskExecutorFactory _sut; /// @@ -46,11 +47,15 @@ public class ScheduledTaskExecutorFactoryTests Substitute.For(), Substitute.For>(), Substitute.For()); + _mockTechnicalDataCleanupTaskExecutor = Substitute.For( + Substitute.For>(), + Substitute.For()); _mockServiceProvider.GetService(typeof(MediaLibraryScanTaskExecutor)).Returns(_mockMediaLibraryScanTaskExecutor); _mockServiceProvider.GetService(typeof(TemporaryFilesCleanupTaskExecutor)).Returns(_mockTemporaryFilesCleanupTaskExecutor); _mockServiceProvider.GetService(typeof(RepairThemesTaskExecutor)).Returns(_mockRepairThemesTaskExecutor); _mockServiceProvider.GetService(typeof(CleanScheduledJobExecutionHistoryTaskExecutor)).Returns(_mockCleanScheduledJobExecutionHistoryTaskExecutor); + _mockServiceProvider.GetService(typeof(TechnicalDataCleanupTaskExecutor)).Returns(_mockTechnicalDataCleanupTaskExecutor); _sut = new ScheduledTaskExecutorFactory(_mockServiceProvider); } @@ -95,6 +100,16 @@ public class ScheduledTaskExecutorFactoryTests Assert.Same(_mockCleanScheduledJobExecutionHistoryTaskExecutor, result); } + [Fact] + public void CreateExecutor_WhenTaskTypeIsTechnicalDataCleanup_ShouldReturnTechnicalDataCleanupTaskExecutor() + { + // Act + IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.TechnicalDataCleanup); + + // Assert + Assert.Same(_mockTechnicalDataCleanupTaskExecutor, result); + } + [Fact] public void CreateExecutor_WhenTaskTypeIsUnsupported_ShouldThrowArgumentException() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs index da6291a3..6df55da8 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; @@ -34,6 +35,7 @@ public class RepairThemesTaskExecutorTests private readonly IThemeRepository _mockThemeRepository; private readonly RepairThemesTaskExecutor _sut; private readonly ScheduledJobFixture _scheduledJobFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -55,7 +57,7 @@ public class RepairThemesTaskExecutorTests // Arrange ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); // Act Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); @@ -74,7 +76,7 @@ public class RepairThemesTaskExecutorTests _mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]); _mockThemeService.ReadManifestFromArchiveAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest")); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); // Act Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutorTests.cs new file mode 100644 index 00000000..5cc7882d --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutorTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TechnicalDataCleanupTaskExecutorTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly TechnicalDataCleanupTaskExecutor _sut; + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TechnicalDataCleanupTaskExecutorTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + ILogger logger = Substitute.For>(); + _sut = new TechnicalDataCleanupTaskExecutor(logger, _mockUnitOfWork); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenCalled_ShouldFailTheInterruptedScans() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup); + _mockLibraryScanRepository.FailInterruptedScansAsync(Arg.Any()).Returns(Result.Updated); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryScanRepository.Received(1).FailInterruptedScansAsync(Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenFailingTheInterruptedScansFails_ShouldReturnTheError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup); + Error expectedError = Error.Failure("Database.Error", "Failed to fail the interrupted scans"); + _mockLibraryScanRepository.FailInterruptedScansAsync(Arg.Any()).Returns(expectedError); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs index 82d89ff7..4a7fe2fd 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs @@ -18,13 +18,14 @@ public class CryptographyServiceTests { private readonly CryptographyService _sut; private readonly IOptions _encryptionSettings; + private readonly CryptographyServiceFixture _cryptographyServiceFixture = new(); /// /// Initializes a new instance of the class. /// public CryptographyServiceTests() { - _encryptionSettings = CryptographyServiceFixture.CreateEncryptionSettings(); + _encryptionSettings = _cryptographyServiceFixture.CreateEncryptionSettings(); _sut = new CryptographyService(_encryptionSettings); } @@ -32,7 +33,7 @@ public class CryptographyServiceTests public void Encrypt_WhenCalledWithValidData_ShouldReturnNonEmptyString() { // Arrange - string plaintext = CryptographyServiceFixture.CreateTestData(); + string plaintext = _cryptographyServiceFixture.CreateTestData(); // Act string result = _sut.Encrypt(plaintext); @@ -47,7 +48,7 @@ public class CryptographyServiceTests public void Encrypt_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentResults() { // Arrange - string plaintext = CryptographyServiceFixture.CreateTestData(); + string plaintext = _cryptographyServiceFixture.CreateTestData(); // Act string result1 = _sut.Encrypt(plaintext); @@ -75,7 +76,7 @@ public class CryptographyServiceTests public void Decrypt_WhenCalledWithValidData_ShouldReturnOriginalText() { // Arrange - string originalText = CryptographyServiceFixture.CreateTestData(); + string originalText = _cryptographyServiceFixture.CreateTestData(); string encrypted = _sut.Encrypt(originalText); // Act @@ -129,10 +130,10 @@ public class CryptographyServiceTests public void Decrypt_WhenInputIsCorrupted_ShouldThrowCryptographicException() { // Arrange - string originalText = CryptographyServiceFixture.CreateTestData(); + string originalText = _cryptographyServiceFixture.CreateTestData(); string encrypted = _sut.Encrypt(originalText); - // decode the Base64 string, modify one byte, then re-encode + // Decode the Base64 string, modify one byte, then re-encode. byte[] encryptedBytes = Convert.FromBase64String(encrypted); encryptedBytes[^1] ^= 0xFF; // flip all bits in the last byte string corrupted = Convert.ToBase64String(encryptedBytes); @@ -148,7 +149,7 @@ public class CryptographyServiceTests public void Dispose_WhenCalled_ShouldClearKey() { // Arrange - string plaintext = CryptographyServiceFixture.CreateTestData(); + string plaintext = _cryptographyServiceFixture.CreateTestData(); string encrypted = _sut.Encrypt(plaintext); // Act diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs index 5c7e7635..4dc26415 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Themes; @@ -37,6 +38,7 @@ public class ThemeSynchronizerTests : IDisposable private readonly ILogger _mockLogger; private readonly ThemeEntityFixture _themeEntityFixture = new(); private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); private readonly string _temporaryDirectoryPath; /// @@ -53,7 +55,7 @@ public class ThemeSynchronizerTests : IDisposable _mockThemeService.GetBundledThemeArchivePaths().Returns([]); _mockThemeService.HasThemePack(Arg.Any()).Returns(true); _mockThemeService.DefaultThemeId.Returns("lumina-default"); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted); @@ -99,7 +101,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [installedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); @@ -117,7 +119,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [deletedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [deletedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); @@ -135,7 +137,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [damagedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); // The first pack check happens before the repair and reports the files as missing; the later checks report the files as present. @@ -157,7 +159,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [damagedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true); @@ -256,7 +258,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [healthyTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [healthyTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); @@ -271,7 +273,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any()).Returns(Result.Success); @@ -289,7 +291,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [lastBundledTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [lastBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -308,7 +310,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenBundledTheme, healthyBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -328,7 +330,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenBundledTheme, healthyBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -348,7 +350,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenUserTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); // Act @@ -363,7 +365,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenUserTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Themes.DeleteFailed", "Failed to delete the theme")); @@ -382,7 +384,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity throwingBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [throwingBundledTheme, healthyBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [throwingBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeService.HasThemePack(Arg.Any()).Returns(false); _mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any()) .Returns(Task.FromException>(new InvalidOperationException("Unexpected failure"))); @@ -403,7 +405,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenBundledTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Task.FromException>(new OperationCanceledException())); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj index ffb0928d..08412e03 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs index f86d2c0d..0eafb831 100644 --- a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs @@ -57,29 +57,29 @@ public class CalibreArtworkProviderTests } [Fact] - public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnNull() + public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnEmpty() { // Arrange MetadataLookupDto lookup = _testMetadataLookupFixture.Create(); IArtworkProvider baseProvider = _sut; // Act - ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await baseProvider.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } [Fact] - public async Task GetArtworkAsync_WhenLookupPathIsEmpty_ShouldReturnNull() + public async Task GetArtworkAsync_WhenLookupPathIsEmpty_ShouldReturnEmpty() { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " "); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } } diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj index 4309ec26..a5cba043 100644 --- a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj @@ -1,10 +1,9 @@ - + net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs index 2172609c..7f90de3f 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs @@ -34,16 +34,16 @@ public class IArtworkProviderGenericTests IArtworkProvider baseProvider = provider; // Act - ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, cancellationToken); + IReadOnlyList result = await baseProvider.GetArtworkAsync(lookup, cancellationToken); // Assert - Assert.Equal(expectedArtwork, result); + Assert.Equal([expectedArtwork], result); Assert.Same(lookup, provider.ReceivedLookup); Assert.Equal(cancellationToken, provider.ReceivedCancellationToken); } [Fact] - public async Task GetArtworkAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnNull() + public async Task GetArtworkAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnEmpty() { // Arrange MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); @@ -51,10 +51,10 @@ public class IArtworkProviderGenericTests IArtworkProvider baseProvider = provider; // Act - ArtworkDto? result = await baseProvider.GetArtworkAsync(otherLookup, CancellationToken.None); + IReadOnlyList result = await baseProvider.GetArtworkAsync(otherLookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); Assert.Null(provider.ReceivedLookup); } @@ -95,11 +95,11 @@ public class IArtworkProviderGenericTests public bool RequiresWebAccess => false; /// - public Task GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + public Task> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) { ReceivedLookup = lookup; ReceivedCancellationToken = cancellationToken; - return Task.FromResult(_artwork); + return Task.FromResult>([_artwork]); } } } diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs index d6413507..a014a6ee 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs @@ -64,7 +64,7 @@ public class IMetadataProviderGenericTests } [Fact] - public async Task GetSearchResultsAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() + public async Task GetSearchResultsAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnEmptyAndNotForward() { // Arrange MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); @@ -72,18 +72,15 @@ public class IMetadataProviderGenericTests IMetadataProvider baseProvider = provider; // Act - async Task Act() - { - await baseProvider.GetSearchResultsAsync(otherLookup, CancellationToken.None); - } + IReadOnlyList result = await baseProvider.GetSearchResultsAsync(otherLookup, CancellationToken.None); // Assert - await Assert.ThrowsAsync(Act); + Assert.Empty(result); Assert.Null(provider.ReceivedLookup); } [Fact] - public async Task GetMetadataAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() + public async Task GetMetadataAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnNullAndNotForward() { // Arrange MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); @@ -91,16 +88,27 @@ public class IMetadataProviderGenericTests IMetadataProvider baseProvider = provider; // Act - async Task Act() - { - await baseProvider.GetMetadataAsync(otherLookup, CancellationToken.None); - } + MetadataDto? result = await baseProvider.GetMetadataAsync(otherLookup, CancellationToken.None); // Assert - await Assert.ThrowsAsync(Act); + Assert.Null(result); Assert.Null(provider.ReceivedLookup); } + [Fact] + public void LookupType_WhenReadThroughBaseInterface_ShouldReturnTypedLookupType() + { + // Arrange + TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Exact Result", includeReleaseInfo: false, includeGenres: false, includeTags: false, includeLanguage: false, includeFormat: false, includeVolumeNumber: false)); + IMetadataProvider baseProvider = provider; + + // Act + Type lookupType = baseProvider.LookupType; + + // Assert + Assert.Equal(typeof(BookMetadataLookupDto), lookupType); + } + /// /// Test double for the typed metadata provider interface that records the forwarded arguments. /// diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj index a70bccb8..f4ca3be7 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs new file mode 100644 index 00000000..9daac4bb --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs @@ -0,0 +1,205 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.CoverArtArchive.Common.DependencyInjection; +using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings; +using Lumina.Plugins.CoverArtArchive.Core.Api; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveServicesTests +{ + [Fact] + public void AddCoverArtArchiveArtworkProvider_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheArtworkProviderForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Single(serviceProvider.GetKeyedServices(pluginId)); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveSettingsProvider)); + Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime); + } + + [Fact] + public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheThrottleAndTheResponseCacheAsSingletons() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor throttleDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveRequestThrottle)); + ServiceDescriptor responseCacheDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveResponseCache)); + Assert.Equal(ServiceLifetime.Singleton, throttleDescriptor.Lifetime); + Assert.Equal(ServiceLifetime.Singleton, responseCacheDescriptor.Lifetime); + } + + [Fact] + public void AddCoverArtArchiveArtworkProvider_WhenCalled_ShouldRegisterTheHttpClient() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid()); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetService()); + } + + [Fact] + public async Task AddCoverArtArchiveArtworkProvider_WhenASettingsCallbackIsProvided_ShouldApplyItToTheDefaults() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId, settings => settings.ContactEmail = "custom@example.com"); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + using (IServiceScope scope = serviceProvider.CreateScope()) + { + CoverArtArchiveSettingsProvider settingsProvider = scope.ServiceProvider.GetRequiredService(); + CoverArtArchiveSettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("custom@example.com", settings.ContactEmail); + } + } + + [Fact] + public void AddCoverArtArchiveArtworkProvider_WhenTheClientIsResolved_ShouldDisableAutomaticRedirectsOnItsPrimaryHandler() + { + // Arrange + ServiceCollection services = new(); + services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid()); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + using (IServiceScope scope = serviceProvider.CreateScope()) + { + // Act + CoverArtArchiveHttpClient client = scope.ServiceProvider.GetRequiredService(); + HttpClientHandler primaryHandler = GetPrimaryHandler(client); + + // Assert + // Automatic redirects must stay disabled on the primary handler, otherwise it would follow a server controlled redirect on its own, + // before the client can check the target host against the Cover Art Archive and the Internet Archive, bypassing that control. + Assert.False(primaryHandler.AllowAutoRedirect); + } + } + + [Fact] + public void AddCoverArtArchiveArtworkProvider_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId); + services.AddCoverArtArchiveArtworkProvider(pluginId: pluginId); + + // Assert + // The settings provider, the throttle and the response cache are registered with TryAdd, so a second call must not add them again. + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveRequestThrottle)); + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveResponseCache)); + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(CoverArtArchiveSettingsProvider)); + } + + /// + /// Gets the primary HTTP message handler of the provided client, unwrapping the delegating handlers built by the HTTP client factory around it. + /// + /// The client whose primary handler is retrieved. + /// The primary HTTP client handler of the client. + private static HttpClientHandler GetPrimaryHandler(CoverArtArchiveHttpClient client) + { + HttpClient httpClient = (HttpClient)GetFieldOfType(client, typeof(HttpClient))!; + HttpMessageHandler? handler = (HttpMessageHandler?)GetFieldOfType(httpClient, typeof(HttpMessageHandler)); + while (handler is DelegatingHandler delegatingHandler) + handler = delegatingHandler.InnerHandler; + return Assert.IsType(handler); + } + + /// + /// Gets the value of the first field, declared on the provided or any of its base types, whose type is assignable to + /// , without relying on the field name, so the test keeps working across runtime versions. + /// + /// The instance whose field is read. + /// The type the field must be assignable to. + /// The value of the found field. + /// Thrown when no field assignable to is found. + private static object GetFieldOfType(object instance, Type fieldType) + { + Type? type = instance.GetType(); + while (type is not null) + { + FieldInfo? field = type + .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly) + .FirstOrDefault(candidate => fieldType.IsAssignableFrom(candidate.FieldType)); + if (field is not null) + return field.GetValue(instance)!; + type = type.BaseType; + } + throw new InvalidOperationException($"No field assignable to {fieldType} was found on {instance.GetType()} or its base types."); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseTests.cs new file mode 100644 index 00000000..2e8d87ec --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveArtworkResponseTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveArtworkResponseTests +{ + [Fact] + public void Deserialize_WhenTheApiReturnsImages_ShouldDeserializeEveryImage() + { + // Arrange + const string JSON = """ + { + "images": [ + { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", "front": true, "types": [ "Front" ] }, + { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/2.jpg", "back": true, "types": [ "Back" ] } + ] + } + """; + + // Act + CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.NotNull(response.Images); + Assert.Equal(2, response.Images.Count); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", response.Images[0]!.Image); + Assert.Equal(["Front"], response.Images[0]!.Types); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/2.jpg", response.Images[1]!.Image); + Assert.Equal(["Back"], response.Images[1]!.Types); + } + + [Fact] + public void Deserialize_WhenTheApiReturnsANullImagesCollection_ShouldDeserializeAsNull() + { + // Arrange + // The API can answer with a null images collection, which must not be turned into anything else by the deserializer. + const string JSON = """{"images":null}"""; + + // Act + CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.Images); + } + + [Fact] + public void Deserialize_WhenTheImagesCollectionContainsNullElements_ShouldKeepThem() + { + // Arrange + const string JSON = """{"images":[null,{"image":"https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg"}]}"""; + + // Act + CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.NotNull(response.Images); + Assert.Equal(2, response.Images.Count); + Assert.Null(response.Images[0]); + Assert.NotNull(response.Images[1]); + } + + [Fact] + public void Deserialize_WhenTheImagesCollectionIsEmpty_ShouldDeserializeAsEmpty() + { + // Arrange + const string JSON = """{"images":[]}"""; + + // Act + CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.NotNull(response.Images); + Assert.Empty(response.Images); + } + + [Fact] + public void Deserialize_WhenThePropertyIsMissing_ShouldDefaultToNull() + { + // Arrange + const string JSON = "{}"; + + // Act + CoverArtArchiveArtworkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.Images); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseTests.cs new file mode 100644 index 00000000..c3461252 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/Models/Contracts/Responses/CoverArtArchiveImageResponseTests.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveImageResponseTests +{ + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "approved": true, + "back": true, + "comment": "A comment", + "front": false, + "id": 12345, + "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345.jpg", + "thumbnail": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345-250.jpg", + "types": [ "Back", "Booklet" ] + } + """; + + // Act + CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345.jpg", response.Image); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/12345-250.jpg", response.Thumbnail); + Assert.Equal(["Back", "Booklet"], response.Types); + Assert.False(response.IsFront); + Assert.True(response.IsBack); + Assert.Equal("A comment", response.Comment); + } + + [Fact] + public void Deserialize_WhenTheApiReturnsANullTypes_ShouldDeserializeAsNull() + { + // Arrange + // The API can answer with a null types collection, which must not be turned into anything else by the deserializer. + const string JSON = """{"image":"https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg","types":null}"""; + + // Act + CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.Types); + } + + [Fact] + public void Deserialize_WhenTheTypesCollectionContainsNullElements_ShouldKeepThem() + { + // Arrange + const string JSON = """{"types":["Front",null,"Booklet"]}"""; + + // Act + CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.NotNull(response.Types); + Assert.Equal(["Front", null, "Booklet"], response.Types); + } + + [Fact] + public void Deserialize_WhenTheApiReturnsANullImage_ShouldDeserializeAsNull() + { + // Arrange + const string JSON = """{"image":null,"types":["Front"]}"""; + + // Act + CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.Image); + } + + [Fact] + public void Deserialize_WhenThePropertiesAreMissing_ShouldDefaultToNullAndFalse() + { + // Arrange + const string JSON = "{}"; + + // Act + CoverArtArchiveImageResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.Image); + Assert.Null(response.Thumbnail); + Assert.Null(response.Types); + Assert.False(response.IsFront); + Assert.False(response.IsBack); + Assert.Null(response.Comment); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs new file mode 100644 index 00000000..3c2efb6d --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Common.TestHelpers; + +/// +/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent. +/// +[ExcludeFromCodeCoverage] +internal sealed class StubHttpMessageHandler : HttpMessageHandler +{ + private readonly Func _responseFactory; + private int _callCount; + + /// + /// Gets the requests that were sent through the handler. + /// + public List Requests { get; } = []; + + /// + /// Gets the number of requests that were sent through the handler. + /// + public int CallCount => _callCount; + + /// + /// Initializes a new instance of the class. + /// + /// The factory that produces the response of a request, given the request and its one based call index. + public StubHttpMessageHandler(Func responseFactory) + { + _responseFactory = responseFactory; + } + + /// + /// Sends the provided request, producing its response through the configured factory. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response produced for the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + int callIndex = Interlocked.Increment(ref _callCount); + Requests.Add(request); + try + { + return Task.FromResult(_responseFactory(request, callIndex)); + } + catch (Exception exception) + { + // A response factory may throw to simulate a transport failure, which is surfaced as a faulted task. + return Task.FromException(exception); + } + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs new file mode 100644 index 00000000..a79ccc3f --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs @@ -0,0 +1,541 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using Lumina.Plugins.CoverArtArchive.Core; +using Lumina.Plugins.CoverArtArchive.Core.Api; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.CoverArtArchive.UnitTests.Common.TestHelpers; +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveHttpClientTests +{ + private const string ARTWORK_JSON = """ + { + "images": [ + { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", "front": true, "types": [ "Front" ] } + ] + } + """; + + private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid s_releaseGroupId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + + private readonly CoverArtArchiveSettingsDtoFixture _coverArtArchiveSettingsDtoFixture = new(); + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheReleaseHasArtwork_ShouldDeserializeIt() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(); + + // Act + CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.Images); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", Assert.Single(result.Images)!.Image); + Assert.Equal($"/release/{s_releaseId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + Assert.Equal("coverartarchive.org", handler.Requests[0].RequestUri!.Host); + } + + [Fact] + public async Task GetReleaseGroupArtworkAsync_WhenTheReleaseGroupHasArtwork_ShouldDeserializeIt() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(); + + // Act + CoverArtArchiveArtworkResponse? result = await client.GetReleaseGroupArtworkAsync(s_releaseGroupId, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.Images); + Assert.Single(result.Images); + Assert.Equal($"/release-group/{s_releaseGroupId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheReleaseIsNotFound_ShouldReturnNull() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + + // Act + CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheSameReleaseIsRequestedTwice_ShouldServeTheSecondRequestFromTheCache() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(); + + // Act + CoverArtArchiveArtworkResponse? first = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + CoverArtArchiveArtworkResponse? second = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.NotNull(first); + Assert.NotNull(second); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheReleaseIsNotFound_ShouldCacheTheAbsence() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + + // Act + CoverArtArchiveArtworkResponse? first = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + CoverArtArchiveArtworkResponse? second = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.Null(first); + Assert.Null(second); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTwoDifferentReleasesAreRequested_ShouldNotShareTheCache() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(); + + // Act + await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + await client.GetReleaseArtworkAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheEndpointRedirectsToTheInternetArchive_ShouldFollowItAndDeserializeTheBody() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => + { + if (callIndex == 1) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri($"https://archive.org/download/mbid-{s_releaseId:D}/index.json"); + return redirect; + } + return CreateJsonResponse(ARTWORK_JSON); + }); + + // Act + CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + Assert.Equal("archive.org", handler.Requests[1].RequestUri!.Host); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheRedirectLocationIsRelative_ShouldResolveItAgainstTheRequest() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => + { + if (callIndex == 1) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri($"/release/{s_releaseId:D}/index.json", UriKind.Relative); + return redirect; + } + return CreateJsonResponse(ARTWORK_JSON); + }); + + // Act + CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + Assert.Equal("coverartarchive.org", handler.Requests[1].RequestUri!.Host); + Assert.Equal($"/release/{s_releaseId:D}/index.json", handler.Requests[1].RequestUri!.AbsolutePath); + } + + [Theory] + [InlineData("https://evil.example/index.json")] // an unrelated public host + [InlineData("https://localhost/index.json")] // the loopback host name + [InlineData("https://127.0.0.1/index.json")] // the IPv4 loopback address + [InlineData("https://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint + public async Task GetReleaseArtworkAsync_WhenTheRedirectPointsAtADisallowedHost_ShouldThrow(string location) + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri(location); + return redirect; + }); + + // Act + Task Act() + { + return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheRedirectDowngradesToPlainHttp_ShouldThrow() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("http://archive.org/index.json"); + return redirect; + }); + + // Act + Task Act() + { + return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheEndpointRedirectsTooManyTimes_ShouldThrow() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/loop/index.json"); + return redirect; + }); + + // Act + Task Act() + { + return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + // The initial request plus the maximum number of followed redirects are sent before the loop is detected. + Assert.Equal(4, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheFirstAttemptReturns503_ShouldRetryAndSucceed() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => callIndex == 1 + ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) + : CreateJsonResponse(ARTWORK_JSON)); + + // Act + CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheFirstAttemptIsRateLimited_ShouldRetryAndSucceed() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => callIndex == 1 + ? new HttpResponseMessage(HttpStatusCode.TooManyRequests) + : CreateJsonResponse(ARTWORK_JSON)); + + // Act + CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheFirstAttemptThrowsATransportException_ShouldRetryAndSucceed() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => callIndex == 1 + ? throw new HttpRequestException("Transient failure.") + : CreateJsonResponse(ARTWORK_JSON)); + + // Act + CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => new HttpResponseMessage(HttpStatusCode.InternalServerError)); + + // Act + Task Act() + { + return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(3, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheFirstAttemptIsRateLimitedWithRetryAfter_ShouldHonorTheRequestedDelay() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient((request, callIndex) => + { + if (callIndex != 1) + return CreateJsonResponse(ARTWORK_JSON); + HttpResponseMessage rateLimited = new(HttpStatusCode.TooManyRequests); + rateLimited.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.Zero); + return rateLimited; + }); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + CoverArtArchiveArtworkResponse? result = await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + // The requested delay of zero is honored instead of the default five hundred millisecond backoff of the first retry. + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(400), $"The elapsed time {stopwatch.Elapsed} shows the Retry-After header was ignored."); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheContactEmailIsConfigured_ShouldIncludeItInTheUserAgent() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(contactEmail: "contact@example.com"); + + // Act + await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + string userAgent = handler.Requests[0].Headers.UserAgent.ToString(); + Assert.Contains("Lumina-Test/1.0", userAgent); + Assert.Contains("contact@example.com", userAgent); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheContactEmailIsNotConfigured_ShouldNotIncludeItInTheUserAgent() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(); + + // Act + await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + string userAgent = handler.Requests[0].Headers.UserAgent.ToString(); + Assert.Equal("Lumina-Test/1.0", userAgent); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheUserAgentIsAlreadySet_ShouldNotOverrideIt() + { + // Arrange + StubHttpMessageHandler handler = new((request, callIndex) => CreateJsonResponse(ARTWORK_JSON)); + HttpClient httpClient = new(handler); + httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Custom/9.9"); + CoverArtArchiveSettingsProvider settingsProvider = CreateSettingsProvider(contactEmail: null); + CoverArtArchiveHttpClient client = new(httpClient, settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache()); + + // Act + await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.Equal("Custom/9.9", handler.Requests[0].Headers.UserAgent.ToString()); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + (CoverArtArchiveHttpClient client, _) = CreateClient(); + + // Act + Task Act() + { + return client.GetReleaseArtworkAsync(s_releaseId, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + [Fact] + public void GetRetryDelay_WhenTheResponseIsNull_ShouldReturnTheExponentialBackoff() + { + // Act + TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, null); + + // Assert + Assert.Equal(TimeSpan.FromMilliseconds(500), result); + } + + [Fact] + public void GetRetryDelay_WhenTheResponseHasNoRetryAfter_ShouldReturnTheExponentialBackoff() + { + // Arrange + HttpResponseMessage response = new(HttpStatusCode.InternalServerError); + + // Act + TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(2, response); + + // Assert + Assert.Equal(TimeSpan.FromSeconds(1), result); + } + + [Fact] + public void GetRetryDelay_WhenTheResponseHasARelativeRetryAfter_ShouldReturnTheRequestedDelay() + { + // Arrange + HttpResponseMessage response = new(HttpStatusCode.TooManyRequests); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(5)); + + // Act + TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response); + + // Assert + Assert.Equal(TimeSpan.FromSeconds(5), result); + } + + [Fact] + public void GetRetryDelay_WhenTheResponseHasARetryAfterOfZero_ShouldReturnZero() + { + // Arrange + HttpResponseMessage response = new(HttpStatusCode.TooManyRequests); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.Zero); + + // Act + TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response); + + // Assert + Assert.Equal(TimeSpan.Zero, result); + } + + [Fact] + public void GetRetryDelay_WhenTheResponseHasAnAbsoluteRetryAfterInTheFuture_ShouldReturnTheRemainingTime() + { + // Arrange + HttpResponseMessage response = new(HttpStatusCode.TooManyRequests); + response.Headers.RetryAfter = new RetryConditionHeaderValue(DateTimeOffset.UtcNow.AddSeconds(5)); + + // Act + TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response); + + // Assert + Assert.True(result > TimeSpan.FromSeconds(4) && result <= TimeSpan.FromSeconds(5), $"The delay {result} was not the remaining time of the absolute Retry-After."); + } + + [Fact] + public void GetRetryDelay_WhenTheResponseHasAnAbsoluteRetryAfterInThePast_ShouldReturnTheExponentialBackoff() + { + // Arrange + HttpResponseMessage response = new(HttpStatusCode.TooManyRequests); + response.Headers.RetryAfter = new RetryConditionHeaderValue(DateTimeOffset.UtcNow.AddSeconds(-5)); + + // Act + TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response); + + // Assert + Assert.Equal(TimeSpan.FromMilliseconds(500), result); + } + + [Fact] + public void GetRetryDelay_WhenTheRequestedDelayExceedsTheMaximum_ShouldCapIt() + { + // Arrange + HttpResponseMessage response = new(HttpStatusCode.TooManyRequests); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromDays(10)); + + // Act + TimeSpan result = CoverArtArchiveHttpClient.GetRetryDelay(1, response); + + // Assert + Assert.Equal(TimeSpan.FromSeconds(60), result); + } + + /// + /// Creates a whose requests are answered by a stub handler, returning the artwork JSON by default. + /// + /// Optional. The factory that produces the response of a request. + /// Optional. The contact email configured for the client. + /// The created client and its stub handler. + private (CoverArtArchiveHttpClient Client, StubHttpMessageHandler Handler) CreateClient( + Func? responseFactory = null, + string? contactEmail = null) + { + StubHttpMessageHandler handler = new(responseFactory ?? ((request, callIndex) => CreateJsonResponse(ARTWORK_JSON))); + CoverArtArchiveSettingsProvider settingsProvider = CreateSettingsProvider(contactEmail); + CoverArtArchiveHttpClient client = new(new HttpClient(handler), settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache()); + return (client, handler); + } + + /// + /// Creates a settings provider configured for the tests, with no throttling. + /// + /// Optional. The contact email configured for the client. + /// The created settings provider. + private CoverArtArchiveSettingsProvider CreateSettingsProvider(string? contactEmail) + { + return new CoverArtArchiveSettingsProvider(null, CoverArtArchivePlugin.s_pluginId, _coverArtArchiveSettingsDtoFixture.Create( + userAgent: "Lumina-Test/1.0", + contactEmail: contactEmail, + includeContactEmail: contactEmail is not null, + minimumRequestInterval: TimeSpan.Zero)); + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage CreateJsonResponse(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveRequestThrottleTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveRequestThrottleTests.cs new file mode 100644 index 00000000..94e1d6ad --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveRequestThrottleTests.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.CoverArtArchive.Core.Api; +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveRequestThrottleTests +{ + private readonly CoverArtArchiveRequestThrottle _sut = new(); + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalHasNotElapsed_ShouldDelayTheSecondRequest() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(200); + + // Act + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + // The second request must wait for the remainder of the interval, which is close to the configured interval. + Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(150), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected minimum interval."); + } + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalIsZero_ShouldNotDelayTheRequests() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.Zero; + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay."); + } + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalIsNegative_ShouldNotDelayTheRequests() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromSeconds(-1); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay."); + } + + [Fact] + public async Task WaitAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + + // Act + Task Act() + { + return _sut.WaitAsync(TimeSpan.FromMilliseconds(100), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + [Fact] + public async Task WaitAsync_WhenCalledConcurrently_ShouldSpaceOutEveryRequest() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(150); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await Task.WhenAll( + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None), + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None), + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None)); + stopwatch.Stop(); + + // Assert + // Three requests spaced by the interval take at least two intervals in total. + Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(250), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected total interval."); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveResponseCacheTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveResponseCacheTests.cs new file mode 100644 index 00000000..b2d0a360 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveResponseCacheTests.cs @@ -0,0 +1,163 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.CoverArtArchive.Core.Api; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveResponseCacheTests +{ + private readonly CoverArtArchiveResponseCache _sut = new(); + + [Fact] + public void TryGet_WhenTheKeyWasNeverCached_ShouldReturnFalse() + { + // Act + bool result = _sut.TryGet("missing", out string? json); + + // Assert + Assert.False(result); + Assert.Null(json); + } + + [Fact] + public void TryGet_WhenTheKeyWasCached_ShouldReturnTheCachedBody() + { + // Arrange + _sut.Set("key", "{\"images\":[]}"); + + // Act + bool result = _sut.TryGet("key", out string? json); + + // Assert + Assert.True(result); + Assert.Equal("{\"images\":[]}", json); + } + + [Fact] + public void Set_WhenTheKeyAlreadyExists_ShouldReplaceTheCachedBody() + { + // Arrange + _sut.Set("key", "a-longer-value"); + _sut.Set("key", "short"); + + // Act + bool result = _sut.TryGet("key", out string? json); + + // Assert + Assert.True(result); + Assert.Equal("short", json); + } + + [Fact] + public void Set_WhenTheValueIsTheEmptyNotFoundMarker_ShouldCacheIt() + { + // Arrange + _sut.Set("release/11111111-1111-1111-1111-111111111111", string.Empty); + + // Act + bool result = _sut.TryGet("release/11111111-1111-1111-1111-111111111111", out string? json); + + // Assert + Assert.True(result); + Assert.Equal(string.Empty, json); + } + + [Fact] + public void Set_WhenTheValueFitsTheCharacterBudgetExactly_ShouldCacheIt() + { + // Arrange + CoverArtArchiveResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1)); + + // Act + sut.Set("exact", "abc"); + + // Assert + Assert.True(sut.TryGet("exact", out string? json)); + Assert.Equal("abc", json); + } + + [Fact] + public void Set_WhenTheValueExceedsTheWholeCharacterBudget_ShouldNotCacheIt() + { + // Arrange + CoverArtArchiveResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1)); + + // Act + sut.Set("oversized", "abcd"); + + // Assert + Assert.False(sut.TryGet("oversized", out _)); + } + + [Fact] + public void Set_WhenTheCharacterBudgetIsExceeded_ShouldEvictTheOldestEntryAndKeepTheNewestOne() + { + // Arrange + CoverArtArchiveResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 10, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("oldest", "1234567890"); + + // Act + sut.Set("newest", "x"); + + // Assert + Assert.False(sut.TryGet("oldest", out _)); + Assert.True(sut.TryGet("newest", out string? json)); + Assert.Equal("x", json); + } + + [Fact] + public void Set_WhenTheEntryCountBudgetIsExceeded_ShouldEvictTheOldestEntriesAndKeepTheNewestOne() + { + // Arrange + CoverArtArchiveResponseCache sut = new(maximumEntryCount: 3, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("entry-1", "1"); + sut.Set("entry-2", "2"); + sut.Set("entry-3", "3"); + + // Act + sut.Set("entry-4", "4"); + + // Assert + // The oldest entries are trimmed to the lower water mark, while the most recently cached one always survives. + Assert.False(sut.TryGet("entry-1", out _)); + Assert.False(sut.TryGet("entry-2", out _)); + Assert.True(sut.TryGet("entry-3", out _)); + Assert.True(sut.TryGet("entry-4", out _)); + } + + [Fact] + public void Set_WhenTheEntryCountBudgetIsExceededByOne_ShouldEvictTheOldestEntryAndKeepTheNewOne() + { + // Arrange + CoverArtArchiveResponseCache sut = new(maximumEntryCount: 1, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("entry-1", "1"); + + // Act + sut.Set("entry-2", "2"); + + // Assert + Assert.True(sut.TryGet("entry-2", out _)); + Assert.False(sut.TryGet("entry-1", out _)); + } + + [Fact] + public void TryGet_WhenTheCachedEntryExpired_ShouldReturnFalse() + { + // Arrange + CoverArtArchiveResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMilliseconds(-1)); + sut.Set("expired", "value"); + + // Act + bool result = sut.TryGet("expired", out string? json); + + // Assert + Assert.False(result); + Assert.Null(json); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveAlbumArtworkProviderTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveAlbumArtworkProviderTests.cs new file mode 100644 index 00000000..ba68eb43 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveAlbumArtworkProviderTests.cs @@ -0,0 +1,275 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.CoverArtArchive.Core; +using Lumina.Plugins.CoverArtArchive.Core.Api; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.CoverArtArchive.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveAlbumArtworkProviderTests +{ + private const string RELEASE_ARTWORK_JSON = """ + { + "images": [ + { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", "front": true, "types": [ "Front" ] }, + { "image": "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", "back": true, "types": [ "Back" ] } + ] + } + """; + + private const string RELEASE_GROUP_ARTWORK_JSON = """ + { + "images": [ + { "image": "https://coverartarchive.org/release-group/22222222-2222-2222-2222-222222222222/front.jpg", "front": true, "types": [ "Front" ] } + ] + } + """; + + private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid s_releaseGroupId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly CoverArtArchiveSettingsDtoFixture _coverArtArchiveSettingsDtoFixture = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, _) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON)); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("Cover Art Archive", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, _) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON)); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnTrue() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, _) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON)); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.True(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheReleaseIdentifierIsPresent_ShouldFetchAndMapTheReleaseArtwork() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(ArtworkType.Cover, result[0].Type); + Assert.Equal(0, result[0].Ordinal); + Assert.Null(result[0].LocalPath); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", result[0].RemoteUrl); + Assert.Equal(ArtworkType.Back, result[1].Type); + Assert.Equal(0, result[1].Ordinal); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", result[1].RemoteUrl); + Assert.Equal(1, handler.CallCount); + Assert.Equal($"/release/{s_releaseId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetArtworkAsync_WhenBothIdentifiersArePresent_ShouldPreferTheRelease() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse( + request.RequestUri!.AbsolutePath.Contains("/release-group/") ? RELEASE_GROUP_ARTWORK_JSON : RELEASE_ARTWORK_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(1, handler.CallCount); + Assert.Equal($"/release/{s_releaseId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheReleaseHasNoArtwork_ShouldFallBackToTheReleaseGroup() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse( + request.RequestUri!.AbsolutePath.Contains("/release-group/") ? RELEASE_GROUP_ARTWORK_JSON : """{"images":[]}""")); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal("https://coverartarchive.org/release-group/22222222-2222-2222-2222-222222222222/front.jpg", artwork.RemoteUrl); + Assert.Equal(2, handler.CallCount); + Assert.Equal($"/release/{s_releaseId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + Assert.Equal($"/release-group/{s_releaseGroupId:D}", handler.Requests[1].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheReleaseIsNotFound_ShouldFallBackToTheReleaseGroup() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.AbsolutePath.Contains("/release-group/") + ? CreateJsonResponse(RELEASE_GROUP_ARTWORK_JSON) + : new HttpResponseMessage(HttpStatusCode.NotFound)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Single(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheReleaseHasNoArtworkAndThereIsNoReleaseGroupIdentifier_ShouldReturnEmpty() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse("""{"images":[]}""")); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheReleaseGroupIdentifierIsPresent_ShouldFetchTheReleaseGroupArtwork() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_GROUP_ARTWORK_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Single(result); + Assert.Equal($"/release-group/{s_releaseGroupId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheReleaseGroupIsNotFound_ShouldReturnEmpty() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetArtworkAsync_WhenThereIsNoIdentifierAtAll_ShouldReturnEmptyWithoutAnyRequest() + { + // Arrange + (CoverArtArchiveAlbumArtworkProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path"); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + (CoverArtArchiveAlbumArtworkProvider sut, _) = CreateProvider((request, callIndex) => CreateJsonResponse(RELEASE_ARTWORK_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + Task Act() + { + return sut.GetArtworkAsync(lookup, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + /// + /// Creates a whose requests are answered by the provided stub handler. + /// + /// The factory that produces the response of a request. + /// The created provider and its stub handler. + private (CoverArtArchiveAlbumArtworkProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func responseFactory) + { + StubHttpMessageHandler handler = new(responseFactory); + CoverArtArchiveSettingsProvider settingsProvider = new(null, CoverArtArchivePlugin.s_pluginId, _coverArtArchiveSettingsDtoFixture.Create( + userAgent: "Lumina-Test/1.0", + includeContactEmail: false, + minimumRequestInterval: TimeSpan.Zero)); + CoverArtArchiveHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new CoverArtArchiveRequestThrottle(), new CoverArtArchiveResponseCache()); + return (new CoverArtArchiveAlbumArtworkProvider(httpClient), handler); + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage CreateJsonResponse(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveHostsTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveHostsTests.cs new file mode 100644 index 00000000..d35c7005 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchiveHostsTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.CoverArtArchive.Core; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveHostsTests +{ + [Theory] + [InlineData("coverartarchive.org")] // the Cover Art Archive host + [InlineData("archive.org")] // the Internet Archive host + [InlineData("ia800100.us.archive.org")] // a subdomain of the Internet Archive that serves its downloads + [InlineData("media.coverartarchive.org")] // a subdomain of the Cover Art Archive + public void IsAllowed_WhenTheHostIsATrustedArchiveHost_ShouldReturnTrue(string host) + { + // Act + bool result = CoverArtArchiveHosts.IsAllowed(host); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData("COVERARTARCHIVE.ORG")] // the Cover Art Archive host, upper cased + [InlineData("Archive.Org")] // the Internet Archive host, mixed cased + public void IsAllowed_WhenTheHostDiffersOnlyByCase_ShouldReturnTrue(string host) + { + // Act + bool result = CoverArtArchiveHosts.IsAllowed(host); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData("")] // an empty host + [InlineData(" ")] // only white space + [InlineData("localhost")] // the loopback host name + [InlineData("127.0.0.1")] // the IPv4 loopback address + [InlineData("169.254.169.254")] // the link local cloud metadata endpoint + [InlineData("10.0.0.5")] // a private class A address + [InlineData("192.168.1.10")] // a private class C address + [InlineData("evil.example")] // an unrelated public host + [InlineData("coverartarchive.org.evil.example")] // the trusted host used as a prefix of an attacker controlled host + [InlineData("archive.org.evil.example")] // the Internet Archive host used as a prefix of an attacker controlled host + [InlineData("notcoverartarchive.org")] // a suffix collision that is not a subdomain + [InlineData("notarchive.org")] // a suffix collision that is not a subdomain + public void IsAllowed_WhenTheHostIsNotATrustedArchiveHost_ShouldReturnFalse(string host) + { + // Act + bool result = CoverArtArchiveHosts.IsAllowed(host); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchivePluginTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchivePluginTests.cs new file mode 100644 index 00000000..056bc9fd --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/CoverArtArchivePluginTests.cs @@ -0,0 +1,121 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.CoverArtArchive.Core; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchivePluginTests +{ + private readonly CoverArtArchivePlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(CoverArtArchivePlugin.s_pluginId, result); + Assert.Equal(new Guid("b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Cover Art Archive", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Retrieves the cover, back, booklet, medium and other artwork of music albums from the Cover Art Archive.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnTheTwoSettingDescriptors() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal( + [ + CoverArtArchiveSettingsKeys.CONTACT_EMAIL, + CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS + ], + result.Select(descriptor => descriptor.Key)); + } + + [Theory] + [InlineData(CoverArtArchiveSettingsKeys.CONTACT_EMAIL, "Contact Email", PluginSettingType.Text, null)] + [InlineData(CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, "Minimum Request Interval (seconds)", PluginSettingType.Number, "1.0")] + public void GetSettingsSchema_WhenCalled_ShouldDescribeEachSettingCorrectly(string key, string label, PluginSettingType type, string? defaultValue) + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + PluginSettingDescriptorDto descriptor = Assert.Single(result, candidate => candidate.Key == key); + Assert.Equal(label, descriptor.Label); + Assert.Equal(type, descriptor.Type); + Assert.Equal(defaultValue, descriptor.DefaultValue); + Assert.Null(descriptor.AllowedValues); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedArtworkProvider() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Single(serviceProvider.GetKeyedServices(CoverArtArchivePlugin.s_pluginId)); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Mapping/CoverArtArchiveMapperTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Mapping/CoverArtArchiveMapperTests.cs new file mode 100644 index 00000000..82273ab1 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Mapping/CoverArtArchiveMapperTests.cs @@ -0,0 +1,397 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; +using Lumina.Plugins.CoverArtArchive.Core.Mapping; +using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.Contracts.Responses; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Mapping; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveMapperTests +{ + private const string COVER_URL = "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg"; + + private readonly CoverArtArchiveArtworkResponseFixture _coverArtArchiveArtworkResponseFixture = new(); + private readonly CoverArtArchiveImageResponseFixture _coverArtArchiveImageResponseFixture = new(); + + [Fact] + public void MapArtwork_WhenTheResponseIsNull_ShouldReturnEmpty() + { + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(null); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void MapArtwork_WhenTheImagesCollectionIsNull_ShouldReturnEmpty() + { + // Arrange + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(includeImages: false); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void MapArtwork_WhenThereAreNoImages_ShouldReturnEmpty() + { + // Arrange + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: []); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void MapArtwork_WhenAnImageElementIsNull_ShouldSkipIt() + { + // Arrange + CoverArtArchiveImageResponse validImage = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [null, validImage]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(COVER_URL, artwork.RemoteUrl); + } + + [Theory] + [InlineData(null)] // a null URL + [InlineData("")] // an empty URL + [InlineData(" ")] // a white space URL + public void MapArtwork_WhenTheImageUrlIsMissing_ShouldSkipIt(string? imageUrl) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: imageUrl, includeImage: imageUrl is not null, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData("not-a-url")] // a value that is not an URI at all + [InlineData("/release/11111111-1111-1111-1111-111111111111/1.jpg")] // a relative URI + [InlineData("coverartarchive.org/release/1.jpg")] // a host without a scheme + public void MapArtwork_WhenTheImageUrlIsNotAnAbsoluteUri_ShouldSkipIt(string imageUrl) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: imageUrl, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData("http://localhost/release/1.jpg")] // the loopback host name + [InlineData("http://127.0.0.1/release/1.jpg")] // the IPv4 loopback address + [InlineData("http://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint + [InlineData("http://10.0.0.5/release/1.jpg")] // a private class A address + [InlineData("http://192.168.1.10/release/1.jpg")] // a private class C address + [InlineData("https://evil.example/release/1.jpg")] // an unrelated public host + [InlineData("https://coverartarchive.org.evil.example/1.jpg")] // the trusted host used as a prefix of an attacker controlled host + [InlineData("https://archive.org.evil.example/1.jpg")] // the Internet Archive host used as a prefix of an attacker controlled host + public void MapArtwork_WhenTheImageUrlPointsAtAnUntrustedHost_ShouldSkipIt(string imageUrl) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: imageUrl, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData("file:///etc/passwd")] // a local file URI + [InlineData("ftp://coverartarchive.org/1.jpg")] // an unsupported scheme on a trusted host + [InlineData("data:image/png;base64,SGVsbG8=")] // an inline data URI + public void MapArtwork_WhenTheImageUrlUsesAnUnsupportedScheme_ShouldSkipIt(string imageUrl) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: imageUrl, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void MapArtwork_WhenTheImageUrlUsesPlainHttpOnATrustedHost_ShouldUpgradeItToHttps() + { + // Arrange + const string HTTP_URL = "http://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg"; + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: HTTP_URL, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/1.jpg", artwork.RemoteUrl); + } + + [Fact] + public void MapArtwork_WhenTheImageUrlUsesHttpsOnATrustedHost_ShouldKeepIt() + { + // Arrange + const string ARCHIVE_URL = "https://archive.org/download/mbid-11111111-1111-1111-1111-111111111111/1.jpg"; + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: ARCHIVE_URL, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ARCHIVE_URL, artwork.RemoteUrl); + } + + [Theory] + [InlineData("front", ArtworkType.Cover)] // the front cover type, lower cased + [InlineData("Front", ArtworkType.Cover)] // the front cover type + [InlineData("BACK", ArtworkType.Back)] // the back cover type, upper cased + [InlineData("Booklet", ArtworkType.Booklet)] // a booklet page + [InlineData("Medium", ArtworkType.Medium)] // a medium label + [InlineData("Tray", ArtworkType.Tray)] // the tray artwork + [InlineData("Spine", ArtworkType.Spine)] // the spine artwork + [InlineData("Obi", ArtworkType.Obi)] // the obi strip + [InlineData("Sticker", ArtworkType.Sticker)] // the sticker + [InlineData("Poster", ArtworkType.Poster)] // the poster + [InlineData("Liner", ArtworkType.Liner)] // the liner notes + [InlineData("Watermark", ArtworkType.Watermark)] // a watermark + [InlineData(" Booklet ", ArtworkType.Booklet)] // a type with surrounding white space + [InlineData("SomeUnknownType", ArtworkType.Other)] // an unknown type is kept as generic artwork + public void MapArtwork_WhenTheImageIsTaggedWithAType_ShouldMapItToTheExpectedArtworkType(string type, ArtworkType expectedArtworkType) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: [type]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(expectedArtworkType, artwork.Type); + Assert.Equal(COVER_URL, artwork.RemoteUrl); + Assert.Equal(0, artwork.Ordinal); + Assert.Null(artwork.LocalPath); + } + + [Fact] + public void MapArtwork_WhenTheTypesAreNullAndTheImageIsFront_ShouldFallBackToCover() + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, includeTypes: false, isFront: true, isBack: false); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + } + + [Fact] + public void MapArtwork_WhenTheTypesAreNullAndTheImageIsBack_ShouldFallBackToBack() + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, includeTypes: false, isFront: false, isBack: true); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Back, artwork.Type); + } + + [Fact] + public void MapArtwork_WhenTheTypesAreNullAndTheImageIsNeitherFrontNorBack_ShouldSkipIt() + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, includeTypes: false, isFront: false, isBack: false); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null element inside the types collection + [InlineData("")] // an empty element inside the types collection + [InlineData(" ")] // a white space element inside the types collection + public void MapArtwork_WhenTheTypesCollectionContainsNullOrEmptyElements_ShouldSkipThem(string? type) + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: [type], isFront: false, isBack: false); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + // With no usable type and no front or back flag, the image describes no artwork at all. + Assert.Empty(result); + } + + [Fact] + public void MapArtwork_WhenTheTypesCollectionContainsDuplicates_ShouldDeDuplicateAndKeepTheResponseOrder() + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: ["Booklet", "Front", "Booklet", "Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(ArtworkType.Booklet, result[0].Type); + Assert.Equal(ArtworkType.Cover, result[1].Type); + } + + [Fact] + public void MapArtwork_WhenAnImageIsTaggedWithSeveralTypes_ShouldEmitThemInTheOrderOfTheResponse() + { + // Arrange + CoverArtArchiveImageResponse image = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: ["Front", "Back", "Booklet"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [image]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Equal(3, result.Count); + Assert.Equal(ArtworkType.Cover, result[0].Type); + Assert.Equal(ArtworkType.Back, result[1].Type); + Assert.Equal(ArtworkType.Booklet, result[2].Type); + } + + [Fact] + public void MapArtwork_WhenSeveralImagesShareAType_ShouldAssignIncrementingOrdinals() + { + // Arrange + CoverArtArchiveImageResponse firstPage = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?page=1", types: ["Booklet"]); + CoverArtArchiveImageResponse secondPage = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?page=2", types: ["Booklet"]); + CoverArtArchiveImageResponse thirdPage = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?page=3", types: ["Booklet"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [firstPage, secondPage, thirdPage]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Equal(3, result.Count); + Assert.All(result, artwork => Assert.Equal(ArtworkType.Booklet, artwork.Type)); + Assert.Equal(0, result[0].Ordinal); + Assert.Equal(1, result[1].Ordinal); + Assert.Equal(2, result[2].Ordinal); + } + + [Fact] + public void MapArtwork_WhenSeveralTypesArePresent_ShouldAssignIndependentOrdinalsPerType() + { + // Arrange + CoverArtArchiveImageResponse cover = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?c=1", types: ["Front"]); + CoverArtArchiveImageResponse booklet = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?b=1", types: ["Booklet"]); + CoverArtArchiveImageResponse secondCover = _coverArtArchiveImageResponseFixture.Create(image: $"{COVER_URL}?c=2", types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [cover, booklet, secondCover]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Equal(3, result.Count); + Assert.Equal(ArtworkType.Cover, result[0].Type); + Assert.Equal(0, result[0].Ordinal); + Assert.Equal(ArtworkType.Booklet, result[1].Type); + Assert.Equal(0, result[1].Ordinal); + Assert.Equal(ArtworkType.Cover, result[2].Type); + Assert.Equal(1, result[2].Ordinal); + } + + [Fact] + public void MapArtwork_WhenEveryFieldIsPresent_ShouldMapEveryArtwork() + { + // Arrange + CoverArtArchiveImageResponse front = _coverArtArchiveImageResponseFixture.Create( + image: "https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", + types: ["Front"], + isFront: true, + isBack: false); + CoverArtArchiveImageResponse backAndMedium = _coverArtArchiveImageResponseFixture.Create( + image: "http://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", + types: ["Back", "Medium"], + isFront: false, + isBack: true); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [front, backAndMedium]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.Equal(3, result.Count); + Assert.Equal(ArtworkType.Cover, result[0].Type); + Assert.Equal(0, result[0].Ordinal); + Assert.Null(result[0].LocalPath); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/front.jpg", result[0].RemoteUrl); + Assert.Equal(ArtworkType.Back, result[1].Type); + Assert.Equal(0, result[1].Ordinal); + Assert.Null(result[1].LocalPath); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", result[1].RemoteUrl); + Assert.Equal(ArtworkType.Medium, result[2].Type); + Assert.Equal(0, result[2].Ordinal); + Assert.Null(result[2].LocalPath); + Assert.Equal("https://coverartarchive.org/release/11111111-1111-1111-1111-111111111111/back.jpg", result[2].RemoteUrl); + } + + [Fact] + public void MapArtwork_WhenCalled_ShouldNeverEmitALocalPath() + { + // Arrange + CoverArtArchiveImageResponse front = _coverArtArchiveImageResponseFixture.Create(image: COVER_URL, types: ["Front"]); + CoverArtArchiveArtworkResponse response = _coverArtArchiveArtworkResponseFixture.Create(images: [front]); + + // Act + IReadOnlyList result = CoverArtArchiveMapper.MapArtwork(response); + + // Assert + Assert.All(result, artwork => Assert.Null(artwork.LocalPath)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Settings/CoverArtArchiveSettingsProviderTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Settings/CoverArtArchiveSettingsProviderTests.cs new file mode 100644 index 00000000..27423268 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Settings/CoverArtArchiveSettingsProviderTests.cs @@ -0,0 +1,212 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings; +using Lumina.Plugins.CoverArtArchive.Core.Settings; +using Lumina.Plugins.CoverArtArchive.Fixtures.Common.Models.DTO.Settings; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.CoverArtArchive.UnitTests.Core.Settings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoverArtArchiveSettingsProviderTests +{ + private readonly CoverArtArchiveSettingsDtoFixture _coverArtArchiveSettingsDtoFixture = new(); + + [Fact] + public async Task GetAsync_WhenNoStoreIsAvailable_ShouldReturnTheDefaults() + { + // Arrange + CoverArtArchiveSettingsDto defaults = CreateDefaults(); + CoverArtArchiveSettingsProvider sut = new(null, Guid.NewGuid(), defaults); + + // Act + CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.NotSame(defaults, result); + Assert.Equal("Lumina-CoverArtArchive/1.0", result.UserAgent); + Assert.Equal("default@example.com", result.ContactEmail); + Assert.Equal(TimeSpan.FromSeconds(1), result.MinimumRequestInterval); + } + + [Fact] + public async Task GetAsync_WhenTheStoreReturnsNoSettings_ShouldReturnTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns((IReadOnlyDictionary?)null); + CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("Lumina-CoverArtArchive/1.0", result.UserAgent); + Assert.Equal("default@example.com", result.ContactEmail); + Assert.Equal(TimeSpan.FromSeconds(1), result.MinimumRequestInterval); + } + + [Fact] + public async Task GetAsync_WhenEverySettingIsPersisted_ShouldOverlayThemOverTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary + { + [CoverArtArchiveSettingsKeys.CONTACT_EMAIL] = " contact@example.com ", + [CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "2.5" + }); + CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("contact@example.com", result.ContactEmail); + Assert.Equal(TimeSpan.FromSeconds(2.5), result.MinimumRequestInterval); + } + + [Theory] + [InlineData("user\r\n@example.com")] // carriage return and line feed injection + [InlineData("user@example.com\r\nX-Injected: value")] // header injection attempt + [InlineData("user(comment)@example.com")] // parentheses break the user agent comment + [InlineData("user\"quoted\"@example.com")] // quotes break the header value + [InlineData("user example@example.com")] // an inner space is not a valid token character + public async Task GetAsync_WhenThePersistedContactEmailContainsUnsafeCharacters_ShouldDropIt(string storedEmail) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [CoverArtArchiveSettingsKeys.CONTACT_EMAIL] = storedEmail }); + CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Null(result.ContactEmail); + } + + [Theory] + [InlineData("", null)] // an empty value clears the email + [InlineData(" ", null)] // a white space value clears the email + [InlineData(" user@example.com ", "user@example.com")] // a value with surrounding white space is trimmed + public async Task GetAsync_WhenThePersistedContactEmailIsPresent_ShouldSetOrClearIt(string storedEmail, string? expectedEmail) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [CoverArtArchiveSettingsKeys.CONTACT_EMAIL] = storedEmail }); + CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedEmail, result.ContactEmail); + } + + [Theory] + [InlineData("2.5", 2.5)] + [InlineData("0", 0)] // an interval of zero is allowed + [InlineData("-3", 0)] // a negative interval is clamped to zero + [InlineData("not-a-number", 1)] // an unparsable value keeps the default + [InlineData("NaN", 1)] // a non finite value keeps the default + [InlineData("Infinity", 1)] // a non finite value keeps the default + [InlineData("-Infinity", 1)] // a non finite value keeps the default + [InlineData("1e400", 1)] // a value that overflows the double range keeps the default + [InlineData("1e308", 60)] // a huge but finite value is clamped to the maximum + [InlineData("1000", 60)] // a value above the maximum is clamped + [InlineData("60", 60)] // the maximum itself is kept + [InlineData("59", 59)] // a value within the range is kept + public async Task GetAsync_WhenThePersistedMinimumRequestIntervalIsPresent_ShouldParseAndClampIt(string storedInterval, double expectedSeconds) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = storedInterval }); + CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + CoverArtArchiveSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(TimeSpan.FromSeconds(expectedSeconds), result.MinimumRequestInterval); + } + + [Fact] + public async Task GetAsync_WhenCalledTwice_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + CoverArtArchiveSettingsDto first = await sut.GetAsync(CancellationToken.None); + CoverArtArchiveSettingsDto second = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Same(first, second); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + CoverArtArchiveSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + CoverArtArchiveSettingsDto[] results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => sut.GetAsync(CancellationToken.None))); + + // Assert + Assert.All(results, result => Assert.Same(results[0], result)); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + CoverArtArchiveSettingsProvider sut = new(null, Guid.NewGuid(), CreateDefaults()); + + // Act + Task Act() + { + return sut.GetAsync(cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + /// + /// Creates the default settings used by the tests of the provider. + /// + /// The default settings. + private CoverArtArchiveSettingsDto CreateDefaults() + { + return _coverArtArchiveSettingsDtoFixture.Create( + userAgent: "Lumina-CoverArtArchive/1.0", + contactEmail: "default@example.com", + minimumRequestInterval: TimeSpan.FromSeconds(1)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests.csproj new file mode 100644 index 00000000..e7c148f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests.csproj @@ -0,0 +1,47 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Lumina.Plugins.Epub.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Lumina.Plugins.Epub.UnitTests.csproj index 0abab51d..67bc13a0 100644 --- a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Lumina.Plugins.Epub.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Lumina.Plugins.Epub.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Common/DependencyInjection/Id3ServicesTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Common/DependencyInjection/Id3ServicesTests.cs new file mode 100644 index 00000000..f637306f --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Common/DependencyInjection/Id3ServicesTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Common.DependencyInjection; +using Lumina.Plugins.ID3.Core.Tags; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3ServicesTests +{ + [Fact] + public void AddId3MetadataProviders_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddId3MetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddId3MetadataProviders_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddId3MetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddId3MetadataProviders_WhenCalled_ShouldRegisterTheThreeMetadataProvidersForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddId3MetadataProviders(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Equal(3, serviceProvider.GetKeyedServices(pluginId).Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void AddId3MetadataProviders_WhenCalled_ShouldRegisterTheTagReaderAsScoped() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddId3MetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor tagReaderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(Id3TagReader)); + Assert.Equal(ServiceLifetime.Scoped, tagReaderDescriptor.Lifetime); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3AlbumMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3AlbumMetadataProviderTests.cs new file mode 100644 index 00000000..c73a3952 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3AlbumMetadataProviderTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3AlbumMetadataProviderTests +{ + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly Id3AlbumMetadataProvider _sut = new(new Id3TagReader()); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("ID3", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + AlbumMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheFileDoesNotExist_ShouldReturnAnEmptyCollection() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3ArtistMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3ArtistMetadataProviderTests.cs new file mode 100644 index 00000000..8573b317 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3ArtistMetadataProviderTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3ArtistMetadataProviderTests +{ + private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new(); + private readonly Id3ArtistMetadataProvider _sut = new(new Id3TagReader()); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("ID3", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + ArtistMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheFileDoesNotExist_ShouldReturnAnEmptyCollection() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3PluginTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3PluginTests.cs new file mode 100644 index 00000000..dee05b5e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3PluginTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3PluginTests +{ + private readonly Id3Plugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(Id3Plugin.s_pluginId, result); + Assert.Equal(new Guid("a3f1c8d2-6b47-4e9a-8c15-2d7f9e4b6a03"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("ID3 Metadata", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Populates artist, album and track metadata from the embedded tags of the audio files, without accessing the web.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheThreeKeyedMetadataProviders() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Equal(3, serviceProvider.GetKeyedServices(Id3Plugin.s_pluginId).Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheTagReader() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetService()); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3TrackMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3TrackMetadataProviderTests.cs new file mode 100644 index 00000000..adc796a3 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3TrackMetadataProviderTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3TrackMetadataProviderTests +{ + private readonly TrackMetadataLookupDtoFixture _trackMetadataLookupDtoFixture = new(); + private readonly Id3TrackMetadataProvider _sut = new(new Id3TagReader()); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("ID3", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + AudioMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheFileDoesNotExist_ShouldReturnAnEmptyCollection() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Mapping/Id3TagMapperTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Mapping/Id3TagMapperTests.cs new file mode 100644 index 00000000..e3013ff1 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Mapping/Id3TagMapperTests.cs @@ -0,0 +1,1286 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Mapping; +using Lumina.Plugins.ID3.Fixtures.Common.Models.DTO.Tags; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core.Mapping; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3TagMapperTests +{ + private readonly Id3TagDtoFixture _id3TagDtoFixture = new(); + + [Fact] + public void MapArtist_WhenTheArtistNameMatchesATrackArtist_ShouldMapEveryArtistField() + { + // Arrange + Guid trackArtistId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Artist"], + albumArtists: ["Some Other Artist"], + trackArtistSortName: "Artist, The", + albumArtistSortName: "Artist, Some Other", + musicBrainzArtistId: trackArtistId.ToString(), + musicBrainzReleaseArtistId: releaseArtistId.ToString(), + website: "https://artist.example"); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Equal("The Artist", result.Name); + Assert.Equal("Artist, The", result.SortName); + Assert.Equal("https://artist.example", result.Website); + Assert.Equal(trackArtistId, result.MusicBrainzArtistId); + Assert.Null(result.Disambiguation); + Assert.Null(result.Type); + Assert.Null(result.Gender); + Assert.Null(result.Country); + Assert.Null(result.Area); + Assert.Null(result.BeginArea); + Assert.Null(result.EndArea); + Assert.Null(result.LifeSpanBegin); + Assert.Null(result.LifeSpanEnd); + Assert.False(result.IsEnded); + Assert.Null(result.Ipis); + Assert.Null(result.Isnis); + Assert.Null(result.Aliases); + Assert.Null(result.Genres); + Assert.Null(result.Tags); + Assert.Null(result.Ratings); + Assert.Null(result.Contributors); + } + + [Fact] + public void MapArtist_WhenTheArtistNameMatchesOnlyAnAlbumArtist_ShouldUseTheAlbumArtistData() + { + // Arrange + Guid trackArtistId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Some Other Artist"], + albumArtists: ["The Artist"], + trackArtistSortName: "Artist, Some Other", + albumArtistSortName: "Artist, The", + musicBrainzArtistId: trackArtistId.ToString(), + musicBrainzReleaseArtistId: releaseArtistId.ToString()); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Equal("The Artist", result.Name); + Assert.Equal("Artist, The", result.SortName); + Assert.Equal(releaseArtistId, result.MusicBrainzArtistId); + } + + [Fact] + public void MapArtist_WhenTheArtistNameIsUnknown_ShouldFallBackToTheAlbumArtist() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + albumArtists: ["Album Artist"], + trackArtistSortName: "Artist, Track", + albumArtistSortName: "Artist, Album"); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "Unknown Artist"); + + // Assert + Assert.Equal("Album Artist", result.Name); + Assert.Equal("Artist, Album", result.SortName); + } + + [Fact] + public void MapArtist_WhenTheArtistNameIsUnknownAndThereAreNoAlbumArtists_ShouldFallBackToTheTrackArtist() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + albumArtists: []); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "Unknown Artist"); + + // Assert + Assert.Equal("Track Artist", result.Name); + } + + [Fact] + public void MapArtist_WhenTheTrackArtistSortNameIsMissing_ShouldFallBackToTheAlbumArtistSortName() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Artist"], + albumArtists: ["Some Other Artist"], + includeTrackArtistSortName: false, + albumArtistSortName: "Artist, Album"); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Equal("Artist, Album", result.SortName); + } + + [Fact] + public void MapArtist_WhenTheAlbumArtistSortNameIsMissing_ShouldFallBackToTheTrackArtistSortName() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Some Other Artist"], + albumArtists: ["The Artist"], + trackArtistSortName: "Artist, Track", + includeAlbumArtistSortName: false); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Equal("Artist, Track", result.SortName); + } + + [Fact] + public void MapArtist_WhenTheUnknownArtistHasOnlyATrackArtistSortName_ShouldUseIt() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + albumArtists: [], + trackArtistSortName: "Artist, Track", + includeAlbumArtistSortName: false); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "Unknown Artist"); + + // Assert + Assert.Equal("Track Artist", result.Name); + Assert.Equal("Artist, Track", result.SortName); + } + + [Fact] + public void MapArtist_WhenTheArtistNameIsWhiteSpace_ShouldFallBackToTheCreditedArtists() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + albumArtists: ["Album Artist"]); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, " "); + + // Assert + Assert.Equal("Album Artist", result.Name); + } + + [Fact] + public void MapArtist_WhenTheIdentifierCannotBeParsed_ShouldReturnNullMusicBrainzArtistId() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Artist"], + musicBrainzArtistId: "not-a-guid", + includeMusicBrainzReleaseArtistId: false); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Null(result.MusicBrainzArtistId); + } + + [Fact] + public void MapAlbum_WhenTheTagsCarryEveryAlbumField_ShouldMapEveryField() + { + // Arrange + Guid releaseId = Guid.NewGuid(); + Guid releaseGroupId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + album: "The Album", + language: "eng", + script: "Latn", + genres: ["Rock"], + releaseTypes: ["album", "live"], + releaseStatus: "official", + mediaFormat: "CD", + packaging: "Jewel Case", + discCount: 2, + trackCount: 12, + barcode: "1234567890123", + catalogNumbers: ["CAT-1", "CAT-2"], + label: "The Label", + asin: "B000000001", + originalReleaseDate: new DateOnly(1975, 11, 21), + originalReleaseYear: 1975, + releaseCountry: "US", + musicBrainzReleaseId: releaseId.ToString(), + musicBrainzReleaseGroupId: releaseGroupId.ToString(), + musicBrainzReleaseArtistId: releaseArtistId.ToString(), + albumArtists: ["The Album Artist"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal("The Album", result.Title); + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Null(result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 11, 21), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry); + Assert.Null(result.ReleaseInfo.ReleaseVersion); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language!.LanguageCode); + Assert.Null(result.OriginalLanguage); + Assert.Null(result.Tags); + Assert.Equal(["Rock"], result.Genres!.Select(genre => genre.Name)); + Assert.Equal("Latn", result.Script); + Assert.Equal([MusicReleaseType.Album, MusicReleaseType.Live], result.ReleaseTypes); + Assert.Equal(MusicReleaseStatus.Official, result.ReleaseStatus); + Assert.Equal(MusicMediaFormat.CD, result.MediaFormat); + Assert.Equal(MusicReleasePackaging.JewelCase, result.Packaging); + Assert.Equal(2, result.TotalDiscs); + Assert.Equal(12, result.TotalTracks); + Assert.Equal("1234567890123", result.Barcode); + Assert.Equal(["CAT-1", "CAT-2"], result.CatalogNumbers); + Assert.Equal("The Label", result.Label); + Assert.Equal("B000000001", result.ASIN); + Assert.Equal(releaseId, result.MusicBrainzReleaseId); + Assert.Equal(releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Album Artist", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Performer, contributor.Role); + Assert.Null(result.Ratings); + Assert.Null(result.ReleaseTitle); + } + + [Fact] + public void MapAlbum_WhenTheTagsAreEmpty_ShouldReturnNullOptionalFields() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + album: "", + includeLanguage: false, + includeScript: false, + genres: [], + releaseTypes: [], + includeReleaseStatus: false, + includeMediaFormat: false, + includePackaging: false, + discCount: 0, + trackCount: 0, + includeBarcode: false, + catalogNumbers: [], + includeLabel: false, + includeAsin: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReleaseCountry: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false, + albumArtists: [], + trackArtists: []); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.ReleaseInfo); + Assert.Null(result.Language); + Assert.Null(result.Genres); + Assert.Null(result.Script); + Assert.Null(result.ReleaseTypes); + Assert.Null(result.ReleaseStatus); + Assert.Null(result.MediaFormat); + Assert.Null(result.Packaging); + Assert.Null(result.TotalDiscs); + Assert.Null(result.TotalTracks); + Assert.Null(result.Barcode); + Assert.Null(result.CatalogNumbers); + Assert.Null(result.Label); + Assert.Null(result.ASIN); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Null(result.Contributors); + } + + [Fact] + public void MapAlbum_WhenGenresAreDuplicated_ShouldKeepOnlyTheDistinctOnes() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(genres: ["Rock", "rock", "ROCK"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(["Rock"], result.Genres!.Select(genre => genre.Name)); + } + + [Fact] + public void MapAlbum_WhenThereIsNoReleaseInformation_ShouldReturnNullReleaseInfo() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReleaseCountry: false); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Fact] + public void MapAlbum_WhenOnlyTheReleaseCountryIsPresent_ShouldBuildTheReleaseInfoFromIt() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + releaseCountry: "US"); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo!.ReleaseCountry); + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.OriginalReleaseYear); + } + + [Fact] + public void MapAlbum_WhenTheReleaseCountryIsUnknown_ShouldReturnNullReleaseCountry() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + releaseCountry: "not-a-country"); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Theory] + [InlineData("eng", "en", "English")] // a three letter code maps to the neutral culture + [InlineData("deu", "de", "German")] // another three letter code maps to the neutral culture + [InlineData("en", "en", "English")] // a two letter code maps too + [InlineData("zxx", "zxx", "No linguistic content")] // the special code of MusicBrainz + [InlineData("mul", "mul", "Multiple languages")] // the special code of MusicBrainz + [InlineData("und", "und", "Undetermined")] // the special code of MusicBrainz + [InlineData("eng/ara", "en", "English")] // only the first code of a multi language tag is used + public void MapAlbum_WhenTheLanguageCodeIsPresent_ShouldMapIt(string language, string expectedCode, string expectedName) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(language: language); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.NotNull(result.Language); + Assert.Equal(expectedCode, result.Language!.LanguageCode); + Assert.Equal(expectedName, result.Language.LanguageName); + } + + [Fact] + public void MapAlbum_WhenTheLanguageCodeIsUnknown_ShouldFallBackToTheRawCode() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(language: "qqq"); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.NotNull(result.Language); + Assert.Equal("qqq", result.Language!.LanguageCode); + Assert.Equal("qqq", result.Language.LanguageName); + Assert.Null(result.Language.NativeName); + } + + [Theory] + [InlineData("official", MusicReleaseStatus.Official)] + [InlineData("promotion", MusicReleaseStatus.Promotion)] + [InlineData("bootleg", MusicReleaseStatus.Bootleg)] + [InlineData("pseudo-release", MusicReleaseStatus.PseudoRelease)] + [InlineData("withdrawn", MusicReleaseStatus.Withdrawn)] + [InlineData("cancelled", MusicReleaseStatus.Cancelled)] + [InlineData("expunged", MusicReleaseStatus.Expunged)] + public void MapAlbum_WhenTheReleaseStatusIsKnown_ShouldMapIt(string status, MusicReleaseStatus expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseStatus: status); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(expected, result.ReleaseStatus); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapAlbum_WhenTheReleaseStatusIsUnknown_ShouldReturnNullStatus(string? status) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseStatus: status); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.ReleaseStatus); + } + + [Theory] + [InlineData("album", MusicReleaseType.Album)] + [InlineData("single", MusicReleaseType.Single)] + [InlineData("ep", MusicReleaseType.Ep)] + [InlineData("broadcast", MusicReleaseType.Broadcast)] + [InlineData("other", MusicReleaseType.Other)] + [InlineData("compilation", MusicReleaseType.Compilation)] + [InlineData("live", MusicReleaseType.Live)] + [InlineData("soundtrack", MusicReleaseType.Soundtrack)] + [InlineData("spokenword", MusicReleaseType.SpokenWord)] + [InlineData("audio drama", MusicReleaseType.AudioDrama)] + [InlineData("audiobook", MusicReleaseType.AudioBook)] + [InlineData("demo", MusicReleaseType.Demo)] + [InlineData("dj-mix", MusicReleaseType.DjMix)] + [InlineData("field recording", MusicReleaseType.FieldRecording)] + [InlineData("interview", MusicReleaseType.Interview)] + [InlineData("mixtape/street", MusicReleaseType.Mixtape)] + [InlineData("remix", MusicReleaseType.Remix)] + public void MapAlbum_WhenTheReleaseTypeIsKnown_ShouldMapIt(string releaseType, MusicReleaseType expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseTypes: [releaseType]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal([expected], result.ReleaseTypes); + } + + [Fact] + public void MapAlbum_WhenSomeReleaseTypesAreUnknown_ShouldKeepOnlyTheKnownOnesWithoutDuplicates() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseTypes: ["made-up", "album", "Album"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal([MusicReleaseType.Album], result.ReleaseTypes); + } + + [Fact] + public void MapAlbum_WhenEveryReleaseTypeIsEmptyOrUnknown_ShouldReturnNullReleaseTypes() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseTypes: ["", " ", "made-up"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.ReleaseTypes); + } + + [Theory] + [InlineData("12\" vinyl", MusicMediaFormat.Inch12Vinyl)] + [InlineData("10\" vinyl", MusicMediaFormat.Inch10Vinyl)] + [InlineData("7\" vinyl", MusicMediaFormat.Inch7Vinyl)] + [InlineData("3\" vinyl", MusicMediaFormat.Inch3Vinyl)] + [InlineData("vinyl", MusicMediaFormat.Vinyl)] + [InlineData("cd", MusicMediaFormat.CD)] + [InlineData("sacd", MusicMediaFormat.SACD)] + [InlineData("hybrid sacd", MusicMediaFormat.HybridSACD)] + [InlineData("digital media", MusicMediaFormat.DigitalMedia)] + [InlineData("cassette", MusicMediaFormat.Cassette)] + [InlineData("dvd", MusicMediaFormat.DVD)] + [InlineData("dvd-video", MusicMediaFormat.DVDVideo)] + [InlineData("dvd-audio", MusicMediaFormat.DVDAudio)] + [InlineData("blu-ray", MusicMediaFormat.BluRay)] + [InlineData("minidisc", MusicMediaFormat.MiniDisc)] + [InlineData("8cm cd", MusicMediaFormat.Cm8CD)] + [InlineData("dat", MusicMediaFormat.DAT)] + [InlineData("vinyl disc", MusicMediaFormat.VinylDisc)] // parsed through the normalized fallback + [InlineData("other", MusicMediaFormat.Other)] + public void MapAlbum_WhenTheMediaFormatIsKnown_ShouldMapIt(string mediaFormat, MusicMediaFormat expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(mediaFormat: mediaFormat); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(expected, result.MediaFormat); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapAlbum_WhenTheMediaFormatIsUnknown_ShouldReturnNullMediaFormat(string? mediaFormat) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(mediaFormat: mediaFormat); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.MediaFormat); + } + + [Theory] + [InlineData("book", MusicReleasePackaging.Book)] + [InlineData("box", MusicReleasePackaging.Box)] + [InlineData("cardboard/paper sleeve", MusicReleasePackaging.CardboardPaperSleeve)] + [InlineData("jewel case", MusicReleasePackaging.JewelCase)] + [InlineData("digipak", MusicReleasePackaging.Digipak)] + [InlineData("metal tin", MusicReleasePackaging.MetalTin)] + [InlineData("none", MusicReleasePackaging.None)] + [InlineData("other", MusicReleasePackaging.Other)] + public void MapAlbum_WhenThePackagingIsKnown_ShouldMapIt(string packaging, MusicReleasePackaging expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(packaging: packaging); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(expected, result.Packaging); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapAlbum_WhenThePackagingIsUnknown_ShouldReturnNullPackaging(string? packaging) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(packaging: packaging); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.Packaging); + } + + [Fact] + public void MapAlbum_WhenAlbumArtistsArePresent_ShouldMapThemAsPerformerContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + albumArtists: ["Album Artist One", "Album Artist Two"], + trackArtists: ["Track Artist"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + Assert.All(result.Contributors, contributor => Assert.Equal(MediaContributorRole.Performer, contributor.Role)); + Assert.Equal(["Album Artist One", "Album Artist Two"], result.Contributors.Select(contributor => contributor.Name!.DisplayName)); + } + + [Fact] + public void MapAlbum_WhenThereAreNoAlbumArtists_ShouldFallBackToTheTrackArtistsForTheContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(albumArtists: [], trackArtists: ["Track Artist"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("Track Artist", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Performer, contributor.Role); + } + + [Fact] + public void MapAlbum_WhenThereAreNoArtistsAtAll_ShouldReturnNullContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(albumArtists: [], trackArtists: []); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.Contributors); + } + + [Fact] + public void MapTrack_WhenTheTagsCarryEveryTrackField_ShouldMapEveryField() + { + // Arrange + Guid recordingId = Guid.NewGuid(); + Guid releaseTrackId = Guid.NewGuid(); + Guid workId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + title: "The Track", + language: "eng", + script: "Latn", + genres: ["Rock"], + musicKey: "C#m", + bpm: 128, + isrcs: ["US1A2B3C4D5E"], + moods: ["calm"], + durationInSeconds: 215, + sampleRate: 44100, + channels: 2, + bitDepth: 24, + bitrate: 320, + audioCodec: "MPEG Audio", + originalReleaseDate: new DateOnly(1975, 11, 21), + originalReleaseYear: 1975, + releaseCountry: "US", + musicBrainzRecordingId: recordingId.ToString(), + musicBrainzReleaseTrackId: releaseTrackId.ToString(), + musicBrainzWorkId: workId.ToString(), + workTitle: "The Work", + trackArtists: ["The Artist"], + composers: ["The Composer"], + lyricists: ["The Lyricist"], + conductors: ["The Conductor"], + remixers: ["The Remixer"], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Equal("The Track", result.Title); + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Null(result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 11, 21), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language!.LanguageCode); + Assert.Null(result.OriginalLanguage); + Assert.Null(result.Tags); + Assert.Equal(["Rock"], result.Genres!.Select(genre => genre.Name)); + Assert.Equal("Latn", result.Script); + Assert.Equal(MusicKey.CSharpMinor, result.Key); + Assert.Equal(128, result.Bpm); + Assert.False(result.IsVideo); + Assert.NotNull(result.Work); + Assert.Equal(workId, result.Work!.MusicBrainzWorkId); + Assert.Equal("The Work", result.Work.Title); + Assert.Equal("US1A2B3C4D5E", Assert.Single(result.Isrcs!).Value); + Assert.Equal("calm", Assert.Single(result.Moods!).Name); + Assert.Equal(215, result.DurationInSeconds); + Assert.Equal(44100, result.SampleRate); + Assert.Equal(2, result.Channels); + Assert.Equal(24, result.BitDepth); + Assert.Equal(320, result.Bitrate); + Assert.Equal("MPEG Audio", result.AudioCodec); + Assert.Equal(recordingId, result.MusicBrainzRecordingId); + Assert.Equal(releaseTrackId, result.MusicBrainzTrackId); + Assert.Null(result.Ratings); + Assert.Equal(5, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Artist" && contributor.Role == MediaContributorRole.Performer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Composer" && contributor.Role == MediaContributorRole.Composer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Lyricist" && contributor.Role == MediaContributorRole.Lyricist); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Conductor" && contributor.Role == MediaContributorRole.Conductor); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Remixer" && contributor.Role == MediaContributorRole.Remixer); + } + + [Fact] + public void MapTrack_WhenTheTagsAreEmpty_ShouldReturnNullOptionalFields() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + title: "", + includeLanguage: false, + includeScript: false, + genres: [], + includeMusicKey: false, + includeBpm: false, + isrcs: [], + moods: [], + includeDurationInSeconds: false, + includeSampleRate: false, + includeChannels: false, + includeBitDepth: false, + includeBitrate: false, + includeAudioCodec: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReleaseCountry: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzReleaseTrackId: false, + includeMusicBrainzWorkId: false, + includeWorkTitle: false, + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.ReleaseInfo); + Assert.Null(result.Language); + Assert.Null(result.Genres); + Assert.Null(result.Script); + Assert.Null(result.Key); + Assert.Null(result.Bpm); + Assert.Null(result.Work); + Assert.Null(result.Isrcs); + Assert.Null(result.Moods); + Assert.Null(result.DurationInSeconds); + Assert.Null(result.SampleRate); + Assert.Null(result.Channels); + Assert.Null(result.BitDepth); + Assert.Null(result.Bitrate); + Assert.Null(result.AudioCodec); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Null(result.MusicBrainzTrackId); + Assert.Null(result.Contributors); + } + + [Fact] + public void MapTrack_WhenThereIsNoReleaseInformation_ShouldReturnNullReleaseInfo() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReleaseCountry: false); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Fact] + public void MapTrack_WhenOnlyTheReleaseCountryIsPresent_ShouldBuildTheReleaseInfoFromIt() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + releaseCountry: "US"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo!.ReleaseCountry); + } + + [Fact] + public void MapTrack_WhenBothTheWorkIdAndTheWorkTitleArePresent_ShouldMapTheWork() + { + // Arrange + Guid workId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: workId.ToString(), + workTitle: "The Work"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.NotNull(result.Work); + Assert.Equal(workId, result.Work!.MusicBrainzWorkId); + Assert.Equal("The Work", result.Work.Title); + Assert.Null(result.Work.Type); + Assert.Null(result.Work.Languages); + Assert.Null(result.Work.Iswcs); + } + + [Fact] + public void MapTrack_WhenTheWorkIdIsSlashSeparated_ShouldUseTheFirstParsableIdentifier() + { + // Arrange + Guid workId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: $"not-a-guid/{workId}", + workTitle: "The Work"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.NotNull(result.Work); + Assert.Equal(workId, result.Work!.MusicBrainzWorkId); + } + + [Fact] + public void MapTrack_WhenTheWorkTitleIsSlashSeparated_ShouldUseTheFirstValue() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: Guid.NewGuid().ToString(), + workTitle: "The Work/Alternate"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.NotNull(result.Work); + Assert.Equal("The Work", result.Work!.Title); + } + + [Fact] + public void MapTrack_WhenOnlyTheWorkIdIsPresent_ShouldReturnNullWork() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: Guid.NewGuid().ToString(), + includeWorkTitle: false); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Work); + } + + [Fact] + public void MapTrack_WhenOnlyTheWorkTitleIsPresent_ShouldReturnNullWork() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeMusicBrainzWorkId: false, + workTitle: "The Work"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Work); + } + + [Fact] + public void MapTrack_WhenTheWorkIdCannotBeParsed_ShouldReturnNullWork() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: "not-a-guid/also-not-a-guid", + workTitle: "The Work"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Work); + } + + [Theory] + [InlineData("C", MusicKey.CMajor)] + [InlineData("C major", MusicKey.CMajor)] + [InlineData("C maj", MusicKey.CMajor)] + [InlineData("Cm", MusicKey.CMinor)] + [InlineData("C min", MusicKey.CMinor)] + [InlineData("C#m", MusicKey.CSharpMinor)] + [InlineData("C# minor", MusicKey.CSharpMinor)] + [InlineData("Db", MusicKey.CSharpMajor)] + [InlineData("D", MusicKey.DMajor)] + [InlineData("Dm", MusicKey.DMinor)] + [InlineData("D# minor", MusicKey.DSharpMinor)] + [InlineData("E", MusicKey.EMajor)] + [InlineData("Em", MusicKey.EMinor)] + [InlineData("F", MusicKey.FMajor)] + [InlineData("Fm", MusicKey.FMinor)] + [InlineData("G", MusicKey.GMajor)] + [InlineData("Gm", MusicKey.GMinor)] + [InlineData("E\u266d", MusicKey.DSharpMajor)] // the flat sign is normalized to the sharp equivalent + [InlineData("F# major", MusicKey.FSharpMajor)] + [InlineData("Gb", MusicKey.FSharpMajor)] + [InlineData("G#m", MusicKey.GSharpMinor)] + [InlineData("Ab", MusicKey.GSharpMajor)] + [InlineData("A#m", MusicKey.ASharpMinor)] + [InlineData("Bb", MusicKey.ASharpMajor)] + [InlineData("am", MusicKey.AMinor)] + [InlineData("b", MusicKey.BMajor)] + public void MapTrack_WhenTheMusicalKeyIsKnown_ShouldMapIt(string musicKey, MusicKey expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(musicKey: musicKey); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Equal(expected, result.Key); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("H")] + [InlineData("Hm")] + public void MapTrack_WhenTheMusicalKeyIsUnknown_ShouldReturnNullKey(string? musicKey) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(musicKey: musicKey); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Key); + } + + [Fact] + public void MapTrack_WhenTheTrackArtistsArePresent_ShouldMapThemAsPerformerContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("Track Artist", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Performer, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheComposersArePresent_ShouldMapThemAsComposerContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: ["The Composer"], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Composer", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Composer, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheLyricistsArePresent_ShouldMapThemAsLyricistContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: ["The Lyricist"], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Lyricist", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Lyricist, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheConductorsArePresent_ShouldMapThemAsConductorContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: ["The Conductor"], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Conductor", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Conductor, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheRemixersArePresent_ShouldMapThemAsRemixerContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: ["The Remixer"], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Remixer", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Remixer, contributor.Role); + } + + [Theory] + [InlineData("producer", MediaContributorRole.Producer)] + [InlineData("executive producer", MediaContributorRole.ExecutiveProducer)] + [InlineData("backing vocals", MediaContributorRole.BackingVocals)] + [InlineData("vocals", MediaContributorRole.Vocals)] + [InlineData("electric bass", MediaContributorRole.BassGuitar)] + [InlineData("bass", MediaContributorRole.BassGuitar)] + [InlineData("guitar", MediaContributorRole.Guitar)] + [InlineData("drums", MediaContributorRole.Drums)] + [InlineData("membranophone", MediaContributorRole.Drums)] + [InlineData("percussion", MediaContributorRole.Percussion)] + [InlineData("tambourine", MediaContributorRole.Percussion)] + [InlineData("keyboard", MediaContributorRole.Keyboards)] + [InlineData("piano", MediaContributorRole.Piano)] + [InlineData("synthesizer", MediaContributorRole.Synthesizer)] + [InlineData("sampler", MediaContributorRole.Synthesizer)] + [InlineData("violin", MediaContributorRole.Strings)] + [InlineData("trumpet", MediaContributorRole.Brass)] + [InlineData("flute", MediaContributorRole.Woodwinds)] + [InlineData("remix", MediaContributorRole.Remixer)] + [InlineData("mastering", MediaContributorRole.Engineer)] + [InlineData("mix", MediaContributorRole.Mixer)] + [InlineData("arranger", MediaContributorRole.Arranger)] + [InlineData("conductor", MediaContributorRole.Conductor)] + [InlineData("orchestrator", MediaContributorRole.Orchestrator)] + [InlineData("composer", MediaContributorRole.Composer)] + [InlineData("librettist", MediaContributorRole.Lyricist)] + [InlineData("author", MediaContributorRole.Author)] + [InlineData("chorus", MediaContributorRole.Choir)] + [InlineData("member of band", MediaContributorRole.Performer)] + [InlineData("orchestra", MediaContributorRole.Performer)] + [InlineData("made-up role", MediaContributorRole.Other)] + public void MapTrack_WhenInvolvedPeopleArePresent_ShouldMapTheirRoles(string role, MediaContributorRole expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: [(role, "The Person")]); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Person", contributor.Name!.DisplayName); + Assert.Equal(expected, contributor.Role); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void MapTrack_WhenAnInvolvedPersonHasNoRole_ShouldMapThemAsOther(string? role) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: [(role!, "The Person")]); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal(MediaContributorRole.Other, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheSameContributorIsCreditedTwiceWithTheSameRole_ShouldKeepASingleContributor() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Artist", "The Artist"], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Single(result.Contributors!); + } + + [Fact] + public void MapTrack_WhenTheSameNameIsCreditedWithTwoRoles_ShouldKeepBothContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Person"], + composers: ["The Person"], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + } + + [Fact] + public void MapTrack_WhenAContributorNameIsWhiteSpace_ShouldSkipIt() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["", " "], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Contributors); + } + + [Fact] + public void MapTrack_WhenThereAreNoContributors_ShouldReturnNullContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Contributors); + } + + [Fact] + public void MapTrack_WhenTheIsrcsAreDuplicated_ShouldKeepOnlyTheDistinctOnes() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(isrcs: ["US1A2B3C4D5E", "us1a2b3c4d5e"]); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Single(result.Isrcs!); + } + + [Fact] + public void MapTrack_WhenTheMoodsAreDuplicated_ShouldKeepOnlyTheDistinctOnes() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(moods: ["calm", "CALM"]); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Single(result.Moods!); + } + + [Fact] + public void MapTrack_WhenTheMoodsAreAbsent_ShouldReturnNullMoods() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(moods: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Moods); + } + + [Fact] + public void MapTrack_WhenTheGenresAreAbsent_ShouldReturnNullGenres() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(genres: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Genres); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/Id3TagReaderTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/Id3TagReaderTests.cs new file mode 100644 index 00000000..72cb56cf --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/Id3TagReaderTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Tags; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core.Tags; + +/// +/// Contains unit tests for the class, covering the guard branches that do not reach the tagging library. +/// +[ExcludeFromCodeCoverage] +public class Id3TagReaderTests : IDisposable +{ + private readonly Id3TagReader _sut = new(); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3TagReaderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-reader-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Read_WhenPathIsNull_ShouldReturnNull() + { + // Act + Id3TagDto? result = _sut.Read(null!); + + // Assert + Assert.Null(result); + } + + [Theory] + [InlineData("")] // an empty path + [InlineData(" ")] // a white space path + public void Read_WhenPathIsEmptyOrWhiteSpace_ShouldReturnNull(string path) + { + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Read_WhenTheFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "missing.wav"); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.Null(result); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Lumina.Plugins.ID3.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Lumina.Plugins.ID3.UnitTests.csproj new file mode 100644 index 00000000..6c8c9d49 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Lumina.Plugins.ID3.UnitTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Common/DependencyInjection/LocalMusicArtworkServicesTests.cs b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Common/DependencyInjection/LocalMusicArtworkServicesTests.cs new file mode 100644 index 00000000..3da0193d --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Common/DependencyInjection/LocalMusicArtworkServicesTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkServicesTests +{ + [Fact] + public void AddLocalMusicArtworkProviders_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddLocalMusicArtworkProviders_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddLocalMusicArtworkProviders_WhenCalled_ShouldRegisterTheAlbumAndArtistProvidersForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddLocalMusicArtworkProviders(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + IReadOnlyList providers = [.. serviceProvider.GetKeyedServices(pluginId)]; + Assert.Equal(2, providers.Count); + Assert.Contains(providers, provider => provider is LocalMusicAlbumArtworkProvider); + Assert.Contains(providers, provider => provider is LocalMusicArtistArtworkProvider); + Assert.Equal(2, providers.Select(provider => provider.GetType()).Distinct().Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void AddLocalMusicArtworkProviders_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(LocalMusicArtworkSettingsProvider)); + Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime); + } + + [Fact] + public void AddLocalMusicArtworkProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddSettingsProvider() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddLocalMusicArtworkProviders(pluginId: pluginId); + services.AddLocalMusicArtworkProviders(pluginId: pluginId); + + // Assert + // The settings provider is registered with TryAdd, so a second call must not add it again, while the artwork providers stay transient and are added once per call. + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(LocalMusicArtworkSettingsProvider)); + Assert.Equal(4, services.Count(descriptor => descriptor.ServiceType == typeof(IArtworkProvider))); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/LocalMusicArtworkPluginTests.cs b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/LocalMusicArtworkPluginTests.cs new file mode 100644 index 00000000..fccfaccf --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/LocalMusicArtworkPluginTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkPluginTests +{ + private readonly LocalMusicArtworkPlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(LocalMusicArtworkPlugin.s_pluginId, result); + Assert.Equal(new Guid("c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Local Music Artwork", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Reads the artwork of the artists and the albums from the images stored in the folders of a local music library.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnTheSingleSettingDescriptor() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + PluginSettingDescriptorDto descriptor = Assert.Single(result); + Assert.Equal(LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER, descriptor.Key); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldDescribeTheEmbeddedCoverSettingCorrectly() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + PluginSettingDescriptorDto descriptor = Assert.Single(result); + Assert.Equal("Extract embedded album cover image from audio files when it is not already present on disk", descriptor.Label); + Assert.Equal(PluginSettingType.Boolean, descriptor.Type); + Assert.Equal("true", descriptor.DefaultValue); + Assert.Null(descriptor.AllowedValues); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheAlbumAndArtistArtworkProviders() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + IReadOnlyList providers = [.. serviceProvider.GetKeyedServices(LocalMusicArtworkPlugin.s_pluginId)]; + Assert.Equal(2, providers.Count); + Assert.Contains(providers, provider => provider is LocalMusicAlbumArtworkProvider); + Assert.Contains(providers, provider => provider is LocalMusicArtistArtworkProvider); + Assert.Equal(2, providers.Select(provider => provider.GetType()).Distinct().Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/Settings/LocalMusicArtworkSettingsProviderTests.cs b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/Settings/LocalMusicArtworkSettingsProviderTests.cs new file mode 100644 index 00000000..4835b085 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/Settings/LocalMusicArtworkSettingsProviderTests.cs @@ -0,0 +1,223 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Core.Settings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkSettingsProviderTests +{ + private readonly LocalMusicArtworkSettingsDtoFixture _localMusicArtworkSettingsDtoFixture = new(); + + [Fact] + public async Task GetAsync_WhenNoStoreIsAvailable_ShouldReturnTheDefaults() + { + // Arrange + LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: true); + LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), defaults); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.NotSame(defaults, result); + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenNoStoreIsAvailableAndTheDefaultsDisableExtraction_ShouldReturnTheDisabledDefault() + { + // Arrange + LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: false); + LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), defaults); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.False(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenTheStoreReturnsNoSettings_ShouldReturnTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns((IReadOnlyDictionary?)null); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Theory] + [InlineData("false", true, false)] // a stored value disables extraction over a default that enables it + [InlineData("true", false, true)] // a stored value enables extraction over a default that disables it + [InlineData("True", false, true)] // the stored value is parsed without regard to casing + [InlineData("FALSE", true, false)] // the stored value is parsed without regard to casing + public async Task GetAsync_WhenTheSettingIsPersisted_ShouldOverlayItOverTheDefaults(string storedValue, bool defaultValue, bool expectedValue) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = storedValue }); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: defaultValue)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedValue, result.ShouldExtractEmbeddedCover); + } + + [Theory] + [InlineData("not-a-boolean")] + [InlineData("")] + [InlineData(" ")] + [InlineData("1")] + [InlineData("0")] + [InlineData("yes")] + public async Task GetAsync_WhenThePersistedSettingIsNotABoolean_ShouldKeepTheDefault(string storedValue) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = storedValue }); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenThePersistedSettingsDoNotContainTheKey_ShouldKeepTheDefault() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { ["SomeOtherKey"] = "false" }); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenThePersistedKeyHasDifferentCasing_ShouldKeepTheDefault() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { ["shouldextractembeddedcover"] = "false" }); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenThePersistedSettingOverridesTheDefaults_ShouldNotMutateTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = "false" }); + LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: true); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), defaults); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.False(result.ShouldExtractEmbeddedCover); + Assert.True(defaults.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenCalledTwice_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto first = await sut.GetAsync(CancellationToken.None); + LocalMusicArtworkSettingsDto second = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Same(first, second); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto[] results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => sut.GetAsync(CancellationToken.None))); + + // Assert + Assert.All(results, result => Assert.Same(results[0], result)); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + Task Act() + { + return sut.GetAsync(cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + /// + /// Creates the default settings used by the tests of the provider. + /// + /// Whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// The default settings. + private LocalMusicArtworkSettingsDto CreateDefaults(bool shouldExtractEmbeddedCover) + { + return _localMusicArtworkSettingsDtoFixture.Create(shouldExtractEmbeddedCover: shouldExtractEmbeddedCover); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests.csproj new file mode 100644 index 00000000..dc58fe86 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests.csproj @@ -0,0 +1,46 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs new file mode 100644 index 00000000..cb5dca74 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs @@ -0,0 +1,147 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Common.DependencyInjection; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzServicesTests +{ + [Fact] + public void AddMusicBrainzMetadataProviders_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheThreeMetadataProvidersForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Equal(3, serviceProvider.GetKeyedServices(pluginId).Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider)); + Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheThrottleAndTheResponseCacheAsSingletons() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor throttleDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzRequestThrottle)); + ServiceDescriptor responseCacheDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache)); + Assert.Equal(ServiceLifetime.Singleton, throttleDescriptor.Lifetime); + Assert.Equal(ServiceLifetime.Singleton, responseCacheDescriptor.Lifetime); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheHttpClient() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetService()); + } + + [Fact] + public async Task AddMusicBrainzMetadataProviders_WhenASettingsCallbackIsProvided_ShouldApplyItToTheDefaults() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: pluginId, settings => settings.BaseUrl = "http://custom.example/ws/2/"); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + using (IServiceScope scope = serviceProvider.CreateScope()) + { + MusicBrainzSettingsProvider settingsProvider = scope.ServiceProvider.GetRequiredService(); + MusicBrainzSettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("http://custom.example/ws/2/", settings.BaseUrl); + } + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: pluginId); + services.AddMusicBrainzMetadataProviders(pluginId: pluginId); + + // Assert + // The settings provider, the throttle and the response cache are registered with TryAdd, so a second call must not add them again. + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzRequestThrottle)); + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache)); + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs new file mode 100644 index 00000000..6be62d2e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzAliasResponseTests +{ + [Fact] + public void IsEnded_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull() + { + // Arrange + // the MusicBrainz search API can return a null ended flag for aliases, which used to break deserialization into a non-nullable boolean + const string JSON = """{"name":"Rammstein","ended":null}"""; + + // Act + MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.IsEnded); + } + + [Fact] + public void IsEnded_WhenTheMusicBrainzApiReturnsTrue_ShouldDeserializeAsTrue() + { + // Arrange + const string JSON = """{"name":"Rammstein","ended":true}"""; + + // Act + MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.True(response.IsEnded); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "name": "Alias Name", + "sort-name": "Alias Sort Name", + "type": "Artist name", + "locale": "en", + "primary": true, + "begin": "1994-01-01", + "end": "2020-12-31", + "ended": true + } + """; + + // Act + MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Alias Name", response.Name); + Assert.Equal("Alias Sort Name", response.SortName); + Assert.Equal("Artist name", response.Type); + Assert.Equal("en", response.Locale); + Assert.True(response.IsPrimary); + Assert.Equal("1994-01-01", response.Begin); + Assert.Equal("2020-12-31", response.End); + Assert.True(response.IsEnded); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs new file mode 100644 index 00000000..d5f084a6 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzAreaResponseTests +{ + [Fact] + public void SortNameTypeAndIsoCodes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """ + { + "id": "c0e0e0e0-0000-0000-0000-000000000000", + "name": "United Kingdom", + "sort-name": "United Kingdom", + "type": "Country", + "iso-3166-1-codes": [ "GB" ], + "iso-3166-2-codes": [ "GB-ENG" ] + } + """; + + // Act + MusicBrainzAreaResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("United Kingdom", response.SortName); + Assert.Equal("Country", response.Type); + Assert.Equal("GB", Assert.Single(response.Iso3166Part1Codes)); + Assert.Equal("GB-ENG", Assert.Single(response.Iso3166Part2Codes)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "area-id", + "name": "United Kingdom", + "sort-name": "United Kingdom", + "disambiguation": "The United Kingdom of Great Britain", + "type": "Country", + "iso-3166-1-codes": [ "GB" ], + "iso-3166-2-codes": [ "GB-ENG" ] + } + """; + + // Act + MusicBrainzAreaResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("area-id", response.Id); + Assert.Equal("United Kingdom", response.Name); + Assert.Equal("United Kingdom", response.SortName); + Assert.Equal("The United Kingdom of Great Britain", response.Disambiguation); + Assert.Equal("Country", response.Type); + Assert.Equal("GB", Assert.Single(response.Iso3166Part1Codes)); + Assert.Equal("GB-ENG", Assert.Single(response.Iso3166Part2Codes)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs new file mode 100644 index 00000000..72083a42 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzArtistCreditResponseTests +{ + [Fact] + public void NameJoinPhraseAndArtist_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"name":"Freddie Mercury","joinphrase":" & ","artist":{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Freddie Mercury"}}"""; + + // Act + MusicBrainzArtistCreditResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Freddie Mercury", response.Name); + Assert.Equal(" & ", response.JoinPhrase); + Assert.NotNull(response.Artist); + Assert.Equal("Freddie Mercury", response.Artist.Name); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "name": "Freddie Mercury", + "joinphrase": " & ", + "artist": { "id": "artist-id", "name": "Freddie Mercury" } + } + """; + + // Act + MusicBrainzArtistCreditResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Freddie Mercury", response.Name); + Assert.Equal(" & ", response.JoinPhrase); + Assert.NotNull(response.Artist); + Assert.Equal("artist-id", response.Artist.Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs new file mode 100644 index 00000000..70353349 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzArtistResponseTests +{ + [Fact] + public void SortNameTypeCountryAndCodes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """ + { + "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", + "name": "Queen", + "sort-name": "Queen", + "type": "Group", + "gender": null, + "country": "GB", + "life-span": { "begin": "1970", "ended": false }, + "ipis": [ "00000000000" ], + "isnis": [ "0000000000000000" ] + } + """; + + // Act + MusicBrainzArtistResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Queen", response.SortName); + Assert.Equal("Group", response.Type); + Assert.Equal("GB", response.Country); + Assert.Equal("00000000000", Assert.Single(response.Ipis)); + Assert.Equal("0000000000000000", Assert.Single(response.Isnis)); + Assert.NotNull(response.LifeSpan); + Assert.Equal("1970", response.LifeSpan.Begin); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "artist-id", + "name": "Queen", + "sort-name": "Queen", + "disambiguation": "UK rock band", + "type": "Group", + "gender": "Male", + "country": "GB", + "area": { "id": "area-id", "name": "United Kingdom" }, + "begin-area": { "id": "begin-area-id", "name": "London" }, + "end-area": { "id": "end-area-id", "name": "Montreux" }, + "life-span": { "begin": "1970", "end": "1991", "ended": true }, + "isnis": [ "isni-1" ], + "ipis": [ "ipi-1" ], + "aliases": [ { "name": "Queen alias" } ], + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ], + "relations": [ { "type": "member of band", "artist": { "id": "member-id", "name": "Freddie Mercury" } } ], + "rating": { "value": 4.5, "votes-count": 10 } + } + """; + + // Act + MusicBrainzArtistResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("artist-id", response.Id); + Assert.Equal("Queen", response.Name); + Assert.Equal("Queen", response.SortName); + Assert.Equal("UK rock band", response.Disambiguation); + Assert.Equal("Group", response.Type); + Assert.Equal("Male", response.Gender); + Assert.Equal("GB", response.Country); + Assert.NotNull(response.Area); + Assert.Equal("United Kingdom", response.Area.Name); + Assert.NotNull(response.BeginArea); + Assert.Equal("London", response.BeginArea.Name); + Assert.NotNull(response.EndArea); + Assert.Equal("Montreux", response.EndArea.Name); + Assert.NotNull(response.LifeSpan); + Assert.Equal("1970", response.LifeSpan.Begin); + Assert.Equal("isni-1", Assert.Single(response.Isnis)); + Assert.Equal("ipi-1", Assert.Single(response.Ipis)); + Assert.Equal("Queen alias", Assert.Single(response.Aliases).Name); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + Assert.Equal("member of band", Assert.Single(response.Relations).Type); + Assert.NotNull(response.Rating); + Assert.Equal(4.5m, response.Rating.Value); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs new file mode 100644 index 00000000..67f8f072 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzArtistSearchResponseTests +{ + [Fact] + public void CountOffsetAndArtists_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"count":1,"offset":0,"artists":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen"}]}"""; + + // Act + MusicBrainzArtistSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(1, response.Count); + Assert.Equal(0, response.Offset); + Assert.Equal("Queen", Assert.Single(response.Artists).Name); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "count": 2, + "offset": 1, + "artists": [ { "id": "artist-id", "name": "Queen" } ] + } + """; + + // Act + MusicBrainzArtistSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(2, response.Count); + Assert.Equal(1, response.Offset); + Assert.Equal("artist-id", Assert.Single(response.Artists).Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs new file mode 100644 index 00000000..a3400d05 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzLabelInfoResponseTests +{ + [Fact] + public void CatalogNumberAndLabel_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"catalog-number":"EMC 4008","label":{"id":"f0e0e0e0-0000-0000-0000-000000000000","name":"EMI"}}"""; + + // Act + MusicBrainzLabelInfoResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("EMC 4008", response.CatalogNumber); + Assert.NotNull(response.Label); + Assert.Equal("EMI", response.Label.Name); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "catalog-number": "EMC 4008", + "label": { "id": "label-id", "name": "EMI" } + } + """; + + // Act + MusicBrainzLabelInfoResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("EMC 4008", response.CatalogNumber); + Assert.NotNull(response.Label); + Assert.Equal("EMI", response.Label.Name); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs new file mode 100644 index 00000000..71b21dc3 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzLabelResponseTests +{ + [Fact] + public void NameDisambiguationAndLabelCode_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"id":"f0e0e0e0-0000-0000-0000-000000000000","name":"EMI","disambiguation":"EMI Records Ltd.","label-code":1234}"""; + + // Act + MusicBrainzLabelResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("EMI", response.Name); + Assert.Equal("EMI Records Ltd.", response.Disambiguation); + Assert.Equal(1234, response.LabelCode); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "label-id", + "name": "EMI", + "disambiguation": "EMI Records Ltd.", + "label-code": 1234 + } + """; + + // Act + MusicBrainzLabelResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("label-id", response.Id); + Assert.Equal("EMI", response.Name); + Assert.Equal("EMI Records Ltd.", response.Disambiguation); + Assert.Equal(1234, response.LabelCode); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs new file mode 100644 index 00000000..38ee4e0c --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzLifeSpanResponseTests +{ + [Fact] + public void IsEnded_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull() + { + // Arrange + // the MusicBrainz search API returns a null ended flag for artists whose end status is unknown, which used to break deserialization into a non-nullable boolean + const string JSON = """{"begin":"1994-01","ended":null}"""; + + // Act + MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.IsEnded); + } + + [Fact] + public void IsEnded_WhenTheMusicBrainzApiReturnsTrue_ShouldDeserializeAsTrue() + { + // Arrange + const string JSON = """{"begin":"1970-06-27","ended":true}"""; + + // Act + MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.True(response.IsEnded); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "begin": "1970-06-27", + "end": "1991-11-24", + "ended": true + } + """; + + // Act + MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("1970-06-27", response.Begin); + Assert.Equal("1991-11-24", response.End); + Assert.True(response.IsEnded); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs new file mode 100644 index 00000000..1c8ebda1 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzMediumResponseTests +{ + [Fact] + public void PositionFormatAndTrackCount_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"position":1,"title":"Disc 1","format":"CD","track-count":12}"""; + + // Act + MusicBrainzMediumResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(1, response.Position); + Assert.Equal("Disc 1", response.Title); + Assert.Equal("CD", response.Format); + Assert.Equal(12, response.TrackCount); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "position": 2, + "title": "Disc 2", + "format": "Vinyl", + "track-count": 8, + "tracks": [ { "id": "track-id", "number": "A1", "position": 1, "title": "Death on Two Legs" } ] + } + """; + + // Act + MusicBrainzMediumResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(2, response.Position); + Assert.Equal("Disc 2", response.Title); + Assert.Equal("Vinyl", response.Format); + Assert.Equal(8, response.TrackCount); + Assert.Equal("track-id", Assert.Single(response.Tracks).Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs new file mode 100644 index 00000000..675a12a2 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRatingResponseTests +{ + private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web) + { + NumberHandling = JsonNumberHandling.AllowReadingFromString + }; + + [Fact] + public void ValueAndVotesCount_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"value":4.5,"votes-count":10}"""; + + // Act + MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON, s_serializerOptions); + + // Assert + Assert.NotNull(response); + Assert.Equal(4.5m, response.Value); + Assert.Equal(10, response.VotesCount); + } + + [Fact] + public void ValueAndVotesCount_WhenTheMusicBrainzApiReturnsStrings_ShouldStillDeserializeThem() + { + // Arrange + // The MusicBrainz search API sometimes returns the rating numbers as strings. + const string JSON = """{"value":"4.5","votes-count":"10"}"""; + + // Act + MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON, s_serializerOptions); + + // Assert + Assert.NotNull(response); + Assert.Equal(4.5m, response.Value); + Assert.Equal(10, response.VotesCount); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """{"value":4.5,"votes-count":10}"""; + + // Act + MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(4.5m, response.Value); + Assert.Equal(10, response.VotesCount); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs new file mode 100644 index 00000000..195f7f68 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRecordingListResponseTests +{ + [Fact] + public void Recordings_WhenReturnedByTheMusicBrainzIsrcLookup_ShouldDeserialize() + { + // Arrange + const string JSON = """{"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","isrcs":["GBUM71029604"]}]}"""; + + // Act + MusicBrainzRecordingListResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + MusicBrainzRecordingResponse recording = Assert.Single(response.Recordings); + Assert.Equal("Death on Two Legs", recording.Title); + Assert.Equal("GBUM71029604", Assert.Single(recording.Isrcs)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "recordings": [ { "id": "recording-id", "title": "Death on Two Legs", "isrcs": [ "GBUM71029604" ] } ] + } + """; + + // Act + MusicBrainzRecordingListResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + MusicBrainzRecordingResponse recording = Assert.Single(response.Recordings); + Assert.Equal("recording-id", recording.Id); + Assert.Equal("Death on Two Legs", recording.Title); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs new file mode 100644 index 00000000..857e7fe7 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRecordingResponseTests +{ + [Fact] + public void IsVideo_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull() + { + // Arrange + // The MusicBrainz search API returns a null video flag for most recordings, which used to break deserialization into a non-nullable boolean. + const string JSON = """{"id":"8778bb30-2f72-4bc8-8b71-cdbe084036c3","title":"A Kind of Magic","video":null}"""; + + // Act + MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.IsVideo); + } + + [Fact] + public void IsVideo_WhenTheMusicBrainzApiReturnsFalse_ShouldDeserializeAsFalse() + { + // Arrange + const string JSON = """{"id":"8778bb30-2f72-4bc8-8b71-cdbe084036c3","title":"A Kind of Magic","video":false}"""; + + // Act + MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.False(response.IsVideo); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "recording-id", + "title": "Bohemian Rhapsody", + "disambiguation": "album version", + "length": 354000, + "video": true, + "first-release-date": "1975-10-31", + "artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id", "name": "Queen" } } ], + "isrcs": [ "GBUM71029604" ], + "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ], + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ], + "relations": [ { "type": "performance", "work": { "id": "work-id", "title": "Bohemian Rhapsody" } } ], + "rating": { "value": 4.5, "votes-count": 10 } + } + """; + + // Act + MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("recording-id", response.Id); + Assert.Equal("Bohemian Rhapsody", response.Title); + Assert.Equal("album version", response.Disambiguation); + Assert.Equal(354000, response.Length); + Assert.True(response.IsVideo); + Assert.Equal("1975-10-31", response.FirstReleaseDate); + Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name); + Assert.Equal("GBUM71029604", Assert.Single(response.Isrcs)); + Assert.Equal("release-id", Assert.Single(response.Releases).Id); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + Assert.Equal("performance", Assert.Single(response.Relations).Type); + Assert.NotNull(response.Rating); + Assert.Equal(4.5m, response.Rating.Value); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs new file mode 100644 index 00000000..b9ebb79d --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRecordingSearchResponseTests +{ + [Fact] + public void CountOffsetAndRecordings_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"count":1,"offset":0,"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}"""; + + // Act + MusicBrainzRecordingSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(1, response.Count); + Assert.Equal(0, response.Offset); + Assert.Equal("Death on Two Legs", Assert.Single(response.Recordings).Title); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "count": 3, + "offset": 2, + "recordings": [ { "id": "recording-id", "title": "Death on Two Legs" } ] + } + """; + + // Act + MusicBrainzRecordingSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(3, response.Count); + Assert.Equal(2, response.Offset); + Assert.Equal("recording-id", Assert.Single(response.Recordings).Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs new file mode 100644 index 00000000..08e90b41 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRelationResponseTests +{ + [Fact] + public void TypeTargetTypeArtistAndAttributes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """ + { + "type": "producer", + "type-id": "d0e0e0e0-0000-0000-0000-000000000000", + "direction": "backward", + "target-type": "artist", + "artist": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "name": "Roy Thomas Baker" }, + "attributes": [ "producer" ] + } + """; + + // Act + MusicBrainzRelationResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("producer", response.Type); + Assert.Equal("backward", response.Direction); + Assert.Equal("artist", response.TargetType); + Assert.NotNull(response.Artist); + Assert.Equal("Roy Thomas Baker", response.Artist.Name); + Assert.Equal("producer", Assert.Single(response.Attributes)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "type": "producer", + "type-id": "type-id", + "direction": "backward", + "target-type": "artist", + "artist": { "id": "artist-id", "name": "Roy Thomas Baker" }, + "work": { "id": "work-id", "title": "Bohemian Rhapsody" }, + "url": { "id": "url-id", "resource": "https://example.com/" }, + "attributes": [ "producer" ] + } + """; + + // Act + MusicBrainzRelationResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("producer", response.Type); + Assert.Equal("type-id", response.TypeId); + Assert.Equal("backward", response.Direction); + Assert.Equal("artist", response.TargetType); + Assert.NotNull(response.Artist); + Assert.Equal("Roy Thomas Baker", response.Artist.Name); + Assert.NotNull(response.Work); + Assert.Equal("Bohemian Rhapsody", response.Work.Title); + Assert.NotNull(response.Url); + Assert.Equal("https://example.com/", response.Url.Resource); + Assert.Equal("producer", Assert.Single(response.Attributes)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs new file mode 100644 index 00000000..4f4a5711 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseBrowseResponseTests +{ + [Fact] + public void ReleaseCountReleaseOffsetAndReleases_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"release-count":5,"release-offset":2,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"A Night at the Opera"}]}"""; + + // Act + MusicBrainzReleaseBrowseResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(5, response.ReleaseCount); + Assert.Equal(2, response.ReleaseOffset); + Assert.Equal("A Night at the Opera", Assert.Single(response.Releases).Title); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ], + "release-count": 5, + "release-offset": 2 + } + """; + + // Act + MusicBrainzReleaseBrowseResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("release-id", Assert.Single(response.Releases).Id); + Assert.Equal(5, response.ReleaseCount); + Assert.Equal(2, response.ReleaseOffset); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs new file mode 100644 index 00000000..4d594ba5 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseEventResponseTests +{ + [Fact] + public void DateAndArea_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"date":"1975-11-21","area":{"id":"c0e0e0e0-0000-0000-0000-000000000000","name":"United Kingdom","iso-3166-1-codes":["GB"]}}"""; + + // Act + MusicBrainzReleaseEventResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("1975-11-21", response.Date); + Assert.NotNull(response.Area); + Assert.Equal("United Kingdom", response.Area.Name); + Assert.Equal("GB", Assert.Single(response.Area.Iso3166Part1Codes)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "date": "1975-11-21", + "area": { "id": "area-id", "name": "United Kingdom" } + } + """; + + // Act + MusicBrainzReleaseEventResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("1975-11-21", response.Date); + Assert.NotNull(response.Area); + Assert.Equal("area-id", response.Area.Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs new file mode 100644 index 00000000..39a0ce75 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseGroupResponseTests +{ + [Fact] + public void PrimaryTypeSecondaryTypesAndFirstReleaseDate_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """ + { + "id": "22222222-2222-2222-2222-222222222222", + "title": "A Night at the Opera", + "primary-type": "Album", + "secondary-types": [ "Live" ], + "first-release-date": "1975-11-21", + "artist-credit": [ { "name": "Queen", "artist": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35" } } ] + } + """; + + // Act + MusicBrainzReleaseGroupResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Album", response.PrimaryType); + Assert.Equal("Live", Assert.Single(response.SecondaryTypes)); + Assert.Equal("1975-11-21", response.FirstReleaseDate); + Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "release-group-id", + "title": "A Night at the Opera", + "disambiguation": "1975 album", + "primary-type": "Album", + "secondary-types": [ "Live" ], + "first-release-date": "1975-11-21", + "artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id" } } ], + "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ], + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ], + "rating": { "value": 4.5, "votes-count": 10 } + } + """; + + // Act + MusicBrainzReleaseGroupResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("release-group-id", response.Id); + Assert.Equal("A Night at the Opera", response.Title); + Assert.Equal("1975 album", response.Disambiguation); + Assert.Equal("Album", response.PrimaryType); + Assert.Equal("Live", Assert.Single(response.SecondaryTypes)); + Assert.Equal("1975-11-21", response.FirstReleaseDate); + Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name); + Assert.Equal("release-id", Assert.Single(response.Releases).Id); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + Assert.NotNull(response.Rating); + Assert.Equal(4.5m, response.Rating.Value); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs new file mode 100644 index 00000000..57aef8ce --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseGroupSearchResponseTests +{ + [Fact] + public void CountOffsetAndReleaseGroups_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"count":2,"offset":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"A Night at the Opera"}]}"""; + + // Act + MusicBrainzReleaseGroupSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(2, response.Count); + Assert.Equal(1, response.Offset); + Assert.Equal("A Night at the Opera", Assert.Single(response.ReleaseGroups).Title); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "count": 2, + "offset": 1, + "release-groups": [ { "id": "release-group-id", "title": "A Night at the Opera" } ] + } + """; + + // Act + MusicBrainzReleaseGroupSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(2, response.Count); + Assert.Equal(1, response.Offset); + Assert.Equal("release-group-id", Assert.Single(response.ReleaseGroups).Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseTests.cs new file mode 100644 index 00000000..273ec302 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseTests.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseResponseTests +{ + [Fact] + public void Media_WhenTheRequestIncludesRecordings_ShouldDeserializeTheTracksAndTheirRecordingsWithTheirWorks() + { + // Arrange + // The recordings included in a release lookup already carry the fields the per track lookups return, including the work of each recording. + const string JSON = """ + { + "id": "1e14b2d6-8652-3dcc-b60b-4fb5fe79e024", + "title": "A Night at the Opera", + "media": [ + { + "position": 1, + "track-count": 1, + "tracks": [ + { + "id": "b1e2c3d4-0000-0000-0000-000000000000", + "number": "1", + "position": 1, + "title": "Death on Two Legs", + "length": 223293, + "recording": { + "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", + "title": "Death on Two Legs (Dedicated To...)", + "video": null, + "isrcs": [ "GBUM71029604" ], + "relations": [ + { + "target-type": "work", + "type": "performance", + "work": { + "id": "d0e0e0e0-0000-0000-0000-000000000000", + "title": "Death on Two Legs", + "type": "Song", + "languages": [ "eng" ], + "iswcs": [ "T-010.154.482-4" ] + } + } + ] + } + } + ] + } + ] + } + """; + + // Act + MusicBrainzReleaseResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + MusicBrainzMediumResponse medium = Assert.Single(response.Media); + Assert.Equal(1, medium.TrackCount); + MusicBrainzTrackResponse track = Assert.Single(medium.Tracks); + Assert.Equal(1, track.Position); + Assert.NotNull(track.Recording); + Assert.Equal("cb6c5931-436c-38c5-9d24-044f37d1fe35", track.Recording.Id); + Assert.Equal("Death on Two Legs (Dedicated To...)", track.Recording.Title); + Assert.Null(track.Recording.IsVideo); + Assert.Equal("GBUM71029604", Assert.Single(track.Recording.Isrcs)); + MusicBrainzRelationResponse relation = Assert.Single(track.Recording.Relations); + Assert.NotNull(relation.Work); + Assert.Equal("Death on Two Legs", relation.Work.Title); + Assert.Equal("eng", Assert.Single(relation.Work.Languages)); + Assert.Equal("T-010.154.482-4", Assert.Single(relation.Work.Iswcs)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "release-id", + "title": "A Night at the Opera", + "disambiguation": "1975 album", + "status": "Official", + "date": "1975-11-21", + "country": "GB", + "release-events": [ { "date": "1975-11-21", "area": { "id": "area-id", "name": "United Kingdom" } } ], + "barcode": "0094639819524", + "packaging": "Jewel Case", + "text-representation": { "language": "eng", "script": "Latn" }, + "artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id", "name": "Queen" } } ], + "release-group": { "id": "release-group-id", "title": "A Night at the Opera" }, + "label-info": [ { "catalog-number": "EMC 4008", "label": { "id": "label-id", "name": "EMI" } } ], + "media": [ { "position": 1, "title": "Disc 1", "format": "CD", "track-count": 12 } ], + "asin": "B000000000", + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ], + "relations": [ { "type": "producer", "artist": { "id": "artist-id", "name": "Roy Thomas Baker" } } ] + } + """; + + // Act + MusicBrainzReleaseResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("release-id", response.Id); + Assert.Equal("A Night at the Opera", response.Title); + Assert.Equal("1975 album", response.Disambiguation); + Assert.Equal("Official", response.Status); + Assert.Equal("1975-11-21", response.Date); + Assert.Equal("GB", response.Country); + Assert.Equal("1975-11-21", Assert.Single(response.ReleaseEvents).Date); + Assert.Equal("0094639819524", response.Barcode); + Assert.Equal("Jewel Case", response.Packaging); + Assert.NotNull(response.TextRepresentation); + Assert.Equal("eng", response.TextRepresentation.Language); + Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name); + Assert.NotNull(response.ReleaseGroup); + Assert.Equal("A Night at the Opera", response.ReleaseGroup.Title); + Assert.Equal("EMC 4008", Assert.Single(response.LabelInfo).CatalogNumber); + Assert.Equal(1, Assert.Single(response.Media).Position); + Assert.Equal("B000000000", response.Asin); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + Assert.Equal("producer", Assert.Single(response.Relations).Type); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTagResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTagResponseTests.cs new file mode 100644 index 00000000..9093c38a --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTagResponseTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzTagResponseTests +{ + [Fact] + public void NameCountAndDisambiguation_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"name":"rock","disambiguation":"genre","count":5}"""; + + // Act + MusicBrainzTagResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("rock", response.Name); + Assert.Equal("genre", response.Disambiguation); + Assert.Equal(5, response.Count); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "genre-id", + "name": "rock", + "disambiguation": "genre", + "count": 5 + } + """; + + // Act + MusicBrainzTagResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("genre-id", response.Id); + Assert.Equal("rock", response.Name); + Assert.Equal("genre", response.Disambiguation); + Assert.Equal(5, response.Count); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseTests.cs new file mode 100644 index 00000000..8f096aaf --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzTextRepresentationResponseTests +{ + [Fact] + public void LanguageAndScript_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"language":"eng","script":"Latn"}"""; + + // Act + MusicBrainzTextRepresentationResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("eng", response.Language); + Assert.Equal("Latn", response.Script); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """{"language":"eng","script":"Latn"}"""; + + // Act + MusicBrainzTextRepresentationResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("eng", response.Language); + Assert.Equal("Latn", response.Script); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTrackResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTrackResponseTests.cs new file mode 100644 index 00000000..a876e542 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTrackResponseTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzTrackResponseTests +{ + [Fact] + public void NumberPositionLengthAndRecording_WhenTheTrackCarriesARecording_ShouldDeserializeAllOfThem() + { + // Arrange + const string JSON = """ + { + "id": "b1e2c3d4-0000-0000-0000-000000000000", + "number": "A1", + "position": 2, + "title": "Death on Two Legs", + "length": 223293, + "recording": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "title": "Death on Two Legs (Dedicated To...)" } + } + """; + + // Act + MusicBrainzTrackResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("A1", response.Number); + Assert.Equal(2, response.Position); + Assert.Equal(223293, response.Length); + Assert.NotNull(response.Recording); + Assert.Equal("cb6c5931-436c-38c5-9d24-044f37d1fe35", response.Recording.Id); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "track-id", + "number": "A1", + "position": 2, + "title": "Death on Two Legs", + "length": 223293, + "recording": { "id": "recording-id", "title": "Death on Two Legs (Dedicated To...)" } + } + """; + + // Act + MusicBrainzTrackResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("track-id", response.Id); + Assert.Equal("A1", response.Number); + Assert.Equal(2, response.Position); + Assert.Equal("Death on Two Legs", response.Title); + Assert.Equal(223293, response.Length); + Assert.NotNull(response.Recording); + Assert.Equal("recording-id", response.Recording.Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzUrlResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzUrlResponseTests.cs new file mode 100644 index 00000000..483fc72f --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzUrlResponseTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzUrlResponseTests +{ + [Fact] + public void Resource_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"id":"e0e0e0e0-0000-0000-0000-000000000000","resource":"https://www.queenonline.com/"}"""; + + // Act + MusicBrainzUrlResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("e0e0e0e0-0000-0000-0000-000000000000", response.Id); + Assert.Equal("https://www.queenonline.com/", response.Resource); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """{"id":"url-id","resource":"https://www.queenonline.com/"}"""; + + // Act + MusicBrainzUrlResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("url-id", response.Id); + Assert.Equal("https://www.queenonline.com/", response.Resource); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzWorkResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzWorkResponseTests.cs new file mode 100644 index 00000000..28d13fd6 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzWorkResponseTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzWorkResponseTests +{ + [Fact] + public void TypeLanguagesAndIswcs_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"id":"d0e0e0e0-0000-0000-0000-000000000000","title":"Death on Two Legs","type":"Song","languages":["eng"],"iswcs":["T-010.154.482-4"]}"""; + + // Act + MusicBrainzWorkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Song", response.Type); + Assert.Equal("eng", Assert.Single(response.Languages)); + Assert.Equal("T-010.154.482-4", Assert.Single(response.Iswcs)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "work-id", + "title": "Bohemian Rhapsody", + "type": "Song", + "disambiguation": "studio version", + "languages": [ "eng" ], + "iswcs": [ "T-010.154.482-4" ], + "relations": [ { "type": "composer", "artist": { "id": "artist-id", "name": "Freddie Mercury" } } ], + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ] + } + """; + + // Act + MusicBrainzWorkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("work-id", response.Id); + Assert.Equal("Bohemian Rhapsody", response.Title); + Assert.Equal("Song", response.Type); + Assert.Equal("studio version", response.Disambiguation); + Assert.Equal("eng", Assert.Single(response.Languages)); + Assert.Equal("T-010.154.482-4", Assert.Single(response.Iswcs)); + Assert.Equal("composer", Assert.Single(response.Relations).Type); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs new file mode 100644 index 00000000..096cb74d --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; + +/// +/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent. +/// +[ExcludeFromCodeCoverage] +internal sealed class StubHttpMessageHandler : HttpMessageHandler +{ + private readonly Func _responseFactory; + private int _callCount; + + /// + /// Gets the requests that were sent through the handler. + /// + public List Requests { get; } = []; + + /// + /// Gets the number of requests that were sent through the handler. + /// + public int CallCount => _callCount; + + /// + /// Initializes a new instance of the class. + /// + /// The factory that produces the response of a request, given the request and its one based call index. + public StubHttpMessageHandler(Func responseFactory) + { + _responseFactory = responseFactory; + } + + /// + /// Sends the provided request, producing its response through the configured factory. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response produced for the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + int callIndex = Interlocked.Increment(ref _callCount); + Requests.Add(request); + try + { + return Task.FromResult(_responseFactory(request, callIndex)); + } + catch (Exception exception) + { + // A response factory may throw to simulate a transport failure, which is surfaced as a faulted task. + return Task.FromException(exception); + } + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs new file mode 100644 index 00000000..ca3a0f9e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs @@ -0,0 +1,578 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzHttpClientTests +{ + private const string RECORDING_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","video":null}"""; + + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public async Task GetRecordingAsync_WhenTheSameRecordingIsRequestedTwice_ShouldServeTheSecondRequestFromTheCache() + { + // Arrange + Guid recordingId = Guid.NewGuid(); + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero); + + // Act + MusicBrainzRecordingResponse? first = await client.GetRecordingAsync(recordingId, CancellationToken.None); + MusicBrainzRecordingResponse? second = await client.GetRecordingAsync(recordingId, CancellationToken.None); + + // Assert + Assert.NotNull(first); + Assert.NotNull(second); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheBaseUrlIsNotTheRealService_ShouldNotThrottleTheRequests() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost:5000/", TimeSpan.FromSeconds(1)); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + stopwatch.Stop(); + + // Assert + // The configured minimum request interval is one second, but a base URL that is not the real MusicBrainz service is not throttled. + Assert.Equal(2, handler.CallCount); + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500)); + } + + [Theory] + [InlineData("https://musicbrainz.org/ws/2/")] // the real service + [InlineData("https://mirror.musicbrainz.org/ws/2/")] // a subdomain of the real service + public async Task GetRecordingAsync_WhenTheBaseUrlIsTheRealService_ShouldThrottleTheRequests(string baseUrl) + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, HttpClient _) = CreateClient(baseUrl, TimeSpan.FromMilliseconds(100)); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.Equal(2, handler.CallCount); + Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(50), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected throttle interval."); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheBaseUrlIsNotAnAbsoluteUri_ShouldThrow() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("not-a-url", TimeSpan.Zero); + + // Act + Task Act() + { + return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheRequestIsNotAuthorized_ShouldReturnNull() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + + // Act + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero); + + // Act + Task Act() + { + return client.GetRecordingAsync(Guid.NewGuid(), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + [Fact] + public async Task GetRecordingAsync_WhenTheFirstAttemptReturns503_ShouldRetryAndSucceed() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1 + ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) + : Json(RECORDING_JSON)); + + // Act + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheFirstAttemptIsRateLimited_ShouldRetryAndSucceed() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1 + ? new HttpResponseMessage(HttpStatusCode.TooManyRequests) + : Json(RECORDING_JSON)); + + // Act + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheFirstAttemptThrowsATransportException_ShouldRetryAndSucceed() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1 + ? throw new HttpRequestException("Transient failure.") + : Json(RECORDING_JSON)); + + // Act + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => new HttpResponseMessage(HttpStatusCode.InternalServerError)); + + // Act + Task Act() + { + return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(4, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheContactEmailIsConfigured_ShouldIncludeItInTheUserAgent() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, contactEmail: "contact@example.com"); + + // Act + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + string userAgent = handler.Requests[0].Headers.UserAgent.ToString(); + Assert.Contains("Lumina-Test/1.0", userAgent); + Assert.Contains("contact@example.com", userAgent); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheContactEmailIsNotConfigured_ShouldNotIncludeItInTheUserAgent() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero); + + // Act + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + string userAgent = handler.Requests[0].Headers.UserAgent.ToString(); + Assert.Equal("Lumina-Test/1.0", userAgent); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheUserAgentIsAlreadySet_ShouldNotOverrideIt() + { + // Arrange + StubHttpMessageHandler handler = new((request, callIndex) => Json(RECORDING_JSON)); + HttpClient httpClient = new(handler); + httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Custom/9.9"); + MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, "http://localhost/", TimeSpan.Zero, null); + + // Act + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.Equal("Custom/9.9", handler.Requests[0].Headers.UserAgent.ToString()); + } + + [Fact] + public async Task GetArtistAsync_WhenTheArtistExists_ShouldDeserializeIt() + { + // Arrange + const string ARTIST_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen","type":"Group"}"""; + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(ARTIST_JSON)); + + // Act + MusicBrainzArtistResponse? result = await client.GetArtistAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Queen", result.Name); + Assert.Contains("inc=aliases+tags+genres+url-rels+artist-rels+ratings", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task SearchArtistsAsync_WhenTheSearchReturnsArtists_ShouldReturnThem() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen"}]}"""; + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON)); + + // Act + IReadOnlyList result = await client.SearchArtistsAsync("Queen", 10, CancellationToken.None); + + // Assert + Assert.Equal("Queen", Assert.Single(result).Name); + Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task SearchArtistsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.SearchArtistsAsync("Queen", 10, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(0, "limit=1")] // a limit below the minimum is clamped up + [InlineData(200, "limit=100")] // a limit above the maximum is clamped down + [InlineData(50, "limit=50")] // a limit within the range is kept + public async Task SearchArtistsAsync_WhenTheLimitIsOutOfRange_ShouldClampIt(int requestedLimit, string expectedQuery) + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("""{"artists":[]}""")); + + // Act + await client.SearchArtistsAsync("Queen", requestedLimit, CancellationToken.None); + + // Assert + Assert.Contains(expectedQuery, handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetReleaseGroupAsync_WhenTheReleaseGroupExists_ShouldDeserializeIt() + { + // Arrange + const string RELEASE_GROUP_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_GROUP_JSON)); + + // Act + MusicBrainzReleaseGroupResponse? result = await client.GetReleaseGroupAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("A Night at the Opera", result.Title); + } + + [Fact] + public async Task SearchReleaseGroupsAsync_WhenTheSearchReturnsReleaseGroups_ShouldReturnThem() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}]}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON)); + + // Act + IReadOnlyList result = await client.SearchReleaseGroupsAsync("Opera", 10, CancellationToken.None); + + // Assert + Assert.Equal("A Night at the Opera", Assert.Single(result).Title); + } + + [Fact] + public async Task SearchReleaseGroupsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.SearchReleaseGroupsAsync("Opera", 10, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetReleaseAsync_WhenTheReleaseExists_ShouldDeserializeIt() + { + // Arrange + const string RELEASE_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_JSON)); + + // Act + MusicBrainzReleaseResponse? result = await client.GetReleaseAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("A Night at the Opera", result.Title); + } + + [Fact] + public async Task BrowseReleasesByReleaseGroupAsync_WhenReleasesExist_ShouldReturnThem() + { + // Arrange + const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}]}"""; + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(BROWSE_JSON)); + + // Act + IReadOnlyList result = await client.BrowseReleasesByReleaseGroupAsync(Guid.NewGuid(), 25, CancellationToken.None); + + // Assert + Assert.Equal("A Night at the Opera", Assert.Single(result).Title); + Assert.Contains("inc=artist-credits+labels+media", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task BrowseReleasesByReleaseGroupAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.BrowseReleasesByReleaseGroupAsync(Guid.NewGuid(), 25, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task SearchRecordingsAsync_WhenTheSearchReturnsRecordings_ShouldReturnThem() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON)); + + // Act + IReadOnlyList result = await client.SearchRecordingsAsync("Death", 10, CancellationToken.None); + + // Assert + Assert.Equal("Death on Two Legs", Assert.Single(result).Title); + } + + [Fact] + public async Task SearchRecordingsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.SearchRecordingsAsync("Death", 10, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetRecordingsByIsrcAsync_WhenRecordingsExist_ShouldReturnThem() + { + // Arrange + const string ISRC_JSON = """{"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(ISRC_JSON)); + + // Act + IReadOnlyList result = await client.GetRecordingsByIsrcAsync("US1A2B3C4D5E", CancellationToken.None); + + // Assert + Assert.Equal("Death on Two Legs", Assert.Single(result).Title); + } + + [Fact] + public async Task GetRecordingsByIsrcAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.GetRecordingsByIsrcAsync("US1A2B3C4D5E", CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetWorkAsync_WhenTheWorkExists_ShouldDeserializeIt() + { + // Arrange + const string WORK_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","type":"Song"}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(WORK_JSON)); + + // Act + MusicBrainzWorkResponse? result = await client.GetWorkAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Death on Two Legs", result.Title); + } + + [Fact] + public async Task GetReleaseWithRecordingsAsync_WhenTheReleaseExists_ShouldDeserializeItsTracks() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", + "title": "A Night at the Opera", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "Death on Two Legs", "recording": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "title": "Death on Two Legs" } } ] } ] + } + """; + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_JSON)); + + // Act + MusicBrainzReleaseResponse? result = await client.GetReleaseWithRecordingsAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Contains("inc=recordings", handler.Requests[0].RequestUri!.Query); + Assert.Single(Assert.Single(result.Media).Tracks); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheFirstAttemptIsRateLimitedWithRetryAfter_ShouldHonorTheRequestedDelay() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => + { + if (callIndex != 1) + return Json(RECORDING_JSON); + HttpResponseMessage rateLimited = new(HttpStatusCode.TooManyRequests); + rateLimited.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.Zero); + return rateLimited; + }); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + // The requested delay of zero is honored instead of the default five hundred millisecond backoff of the first retry. + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(400), $"The elapsed time {stopwatch.Elapsed} shows the Retry-After header was ignored."); + } + + [Theory] + [InlineData("A & B")] // ampersand query separator + [InlineData("Title #fragment")] // fragment separator + [InlineData("A?B")] // query separator + [InlineData("../../secret")] // path traversal + [InlineData("A\" OR \"B")] // quote escape + public async Task SearchArtistsAsync_WhenTheQueryContainsReservedCharacters_ShouldKeepThemInsideTheQueryString(string searchTerm) + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://musicbrainz.example/ws/2/", TimeSpan.Zero, (request, callIndex) => Json("""{"artists":[]}""")); + + // Act + await client.SearchArtistsAsync(searchTerm, 10, CancellationToken.None); + + // Assert + Uri requestUri = handler.Requests[0].RequestUri!; + Assert.Equal("musicbrainz.example", requestUri.Host); + Assert.Equal("/ws/2/artist", requestUri.AbsolutePath); + Assert.Equal(string.Empty, requestUri.Fragment); + } + + /// + /// Creates a whose requests are answered by a stub handler, returning the recording JSON by default. + /// + /// The base URL of the MusicBrainz web service the client points to. + /// The minimum request interval configured for the client. + /// Optional. The factory that produces the response of a request. + /// Optional. The contact email configured for the client. + /// The created client, its stub handler and the underlying HTTP client. + private (MusicBrainzHttpClient Client, StubHttpMessageHandler Handler, HttpClient HttpClient) CreateClient( + string baseUrl, + TimeSpan minimumRequestInterval, + Func? responseFactory = null, + string? contactEmail = null) + { + StubHttpMessageHandler handler = new(responseFactory ?? ((request, callIndex) => Json(RECORDING_JSON))); + HttpClient httpClient = new(handler); + MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, baseUrl, minimumRequestInterval, contactEmail); + return (client, handler, httpClient); + } + + /// + /// Creates a around the provided . + /// + /// The underlying HTTP client. + /// The base URL of the MusicBrainz web service the client points to. + /// The minimum request interval configured for the client. + /// Optional. The contact email configured for the client. + /// The created client. + private MusicBrainzHttpClient CreateMusicBrainzHttpClient(HttpClient httpClient, string baseUrl, TimeSpan minimumRequestInterval, string? contactEmail) + { + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: baseUrl, + userAgent: "Lumina-Test/1.0", + contactEmail: contactEmail, + includeContactEmail: contactEmail is not null, + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: minimumRequestInterval)); + return new MusicBrainzHttpClient(httpClient, settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzRequestThrottleTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzRequestThrottleTests.cs new file mode 100644 index 00000000..bd9e287f --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzRequestThrottleTests.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Core.Api; +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRequestThrottleTests +{ + private readonly MusicBrainzRequestThrottle _sut = new(); + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalHasNotElapsed_ShouldDelayTheSecondRequest() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(200); + + // Act + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + // The second request must wait for the remainder of the interval, which is close to the configured interval. + Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(150), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected minimum interval."); + } + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalIsZero_ShouldNotDelayTheRequests() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.Zero; + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay."); + } + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalIsNegative_ShouldNotDelayTheRequests() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromSeconds(-1); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay."); + } + + [Fact] + public async Task WaitAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + + // Act + Task Act() + { + return _sut.WaitAsync(TimeSpan.FromMilliseconds(100), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + [Fact] + public async Task WaitAsync_WhenCalledConcurrently_ShouldSpaceOutEveryRequest() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(150); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await Task.WhenAll( + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None), + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None), + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None)); + stopwatch.Stop(); + + // Assert + // Three requests spaced by the interval take at least two intervals in total. + Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(250), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected total interval."); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzResponseCacheTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzResponseCacheTests.cs new file mode 100644 index 00000000..14bb54d0 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzResponseCacheTests.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Core.Api; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzResponseCacheTests +{ + private readonly MusicBrainzResponseCache _sut = new(); + + [Fact] + public void TryGet_WhenTheKeyWasNeverCached_ShouldReturnFalse() + { + // Act + bool result = _sut.TryGet("missing", out string? json); + + // Assert + Assert.False(result); + Assert.Null(json); + } + + [Fact] + public void TryGet_WhenTheKeyWasCached_ShouldReturnTheCachedBody() + { + // Arrange + _sut.Set("key", "{\"id\":\"1\"}"); + + // Act + bool result = _sut.TryGet("key", out string? json); + + // Assert + Assert.True(result); + Assert.Equal("{\"id\":\"1\"}", json); + } + + [Fact] + public void Set_WhenTheKeyAlreadyExists_ShouldReplaceTheCachedBody() + { + // Arrange + _sut.Set("key", "a-longer-value"); + _sut.Set("key", "short"); + + // Act + bool result = _sut.TryGet("key", out string? json); + + // Assert + Assert.True(result); + Assert.Equal("short", json); + } + + [Fact] + public void Set_WhenTheValueFitsTheCharacterBudgetExactly_ShouldCacheIt() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1)); + + // Act + sut.Set("exact", "abc"); + + // Assert + Assert.True(sut.TryGet("exact", out string? json)); + Assert.Equal("abc", json); + } + + [Fact] + public void Set_WhenTheValueExceedsTheWholeCharacterBudget_ShouldNotCacheIt() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1)); + + // Act + sut.Set("oversized", "abcd"); + + // Assert + Assert.False(sut.TryGet("oversized", out _)); + } + + [Fact] + public void Set_WhenTheCharacterBudgetIsExceeded_ShouldEvictTheOldestEntryAndKeepTheNewestOne() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 10, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("oldest", "1234567890"); + + // Act + sut.Set("newest", "x"); + + // Assert + Assert.False(sut.TryGet("oldest", out _)); + Assert.True(sut.TryGet("newest", out string? json)); + Assert.Equal("x", json); + } + + [Fact] + public void Set_WhenTheEntryCountBudgetIsExceeded_ShouldEvictTheOldestEntriesAndKeepTheNewestOne() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 3, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("entry-1", "1"); + sut.Set("entry-2", "2"); + sut.Set("entry-3", "3"); + + // Act + sut.Set("entry-4", "4"); + + // Assert + // The oldest entries are trimmed to the lower water mark, while the most recently cached one always survives. + Assert.False(sut.TryGet("entry-1", out _)); + Assert.False(sut.TryGet("entry-2", out _)); + Assert.True(sut.TryGet("entry-3", out _)); + Assert.True(sut.TryGet("entry-4", out _)); + } + + [Fact] + public void Set_WhenTheEntryCountBudgetIsExceededByOne_ShouldEvictTheOldestEntryAndKeepTheNewOne() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 1, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("entry-1", "1"); + + // Act + sut.Set("entry-2", "2"); + + // Assert + Assert.True(sut.TryGet("entry-2", out _)); + Assert.False(sut.TryGet("entry-1", out _)); + } + + [Fact] + public void TryGet_WhenTheCachedEntryExpired_ShouldReturnFalse() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMilliseconds(-1)); + sut.Set("expired", "value"); + + // Act + bool result = sut.TryGet("expired", out string? json); + + // Assert + Assert.False(result); + Assert.Null(json); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Mapping/MusicBrainzMapperTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Mapping/MusicBrainzMapperTests.cs new file mode 100644 index 00000000..91d8eb01 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Mapping/MusicBrainzMapperTests.cs @@ -0,0 +1,1508 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Core.Mapping; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Mapping; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzMapperTests +{ + private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new(); + private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new(); + private readonly MusicBrainzAliasResponseFixture _musicBrainzAliasResponseFixture = new(); + private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzLifeSpanResponseFixture _musicBrainzLifeSpanResponseFixture = new(); + private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new(); + private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new(); + private readonly MusicBrainzReleaseResponseFixture _musicBrainzReleaseResponseFixture = new(); + private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new(); + private readonly MusicBrainzLabelInfoResponseFixture _musicBrainzLabelInfoResponseFixture = new(); + private readonly MusicBrainzMediumResponseFixture _musicBrainzMediumResponseFixture = new(); + private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new(); + private readonly MusicBrainzWorkResponseFixture _musicBrainzWorkResponseFixture = new(); + private readonly MusicBrainzUrlResponseFixture _musicBrainzUrlResponseFixture = new(); + private readonly MusicBrainzTextRepresentationResponseFixture _musicBrainzTextRepresentationResponseFixture = new(); + private readonly MusicBrainzLabelResponseFixture _musicBrainzLabelResponseFixture = new(); + + [Fact] + public void MapArtist_WhenEveryFieldIsPresent_ShouldMapEveryField() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid areaId = Guid.NewGuid(); + Guid beginAreaId = Guid.NewGuid(); + Guid endAreaId = Guid.NewGuid(); + MusicBrainzAreaResponse area = _musicBrainzAreaResponseFixture.Create(id: areaId.ToString(), name: "United States", sortName: "United States", disambiguation: "the country", type: "Country", iso3166Part1Codes: ["US"], iso3166Part2Codes: ["US-NY"]); + MusicBrainzAreaResponse beginArea = _musicBrainzAreaResponseFixture.Create(id: beginAreaId.ToString(), name: "New York", iso3166Part1Codes: ["US"], iso3166Part2Codes: []); + MusicBrainzAreaResponse endArea = _musicBrainzAreaResponseFixture.Create(id: endAreaId.ToString(), name: "Los Angeles", iso3166Part1Codes: ["US"], iso3166Part2Codes: []); + MusicBrainzAliasResponse alias = _musicBrainzAliasResponseFixture.Create(name: "The Alias", sortName: "Alias, The", type: "Artist name", locale: "en", isPrimary: true, begin: "1990-01-01", end: "2000-01-01", isEnded: false); + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + id: artistId.ToString(), + name: " The Artist ", + sortName: "Artist, The", + disambiguation: "UK band", + type: "Group", + gender: "Female", + country: "US", + area: area, + includeArea: true, + beginArea: beginArea, + includeBeginArea: true, + endArea: endArea, + includeEndArea: true, + lifeSpan: _musicBrainzLifeSpanResponseFixture.Create(begin: "1950-01-01", end: "2000-12-31", isEnded: true), + includeLifeSpan: true, + isnis: ["ISNI1", "", " "], + ipis: ["IPI1", "", " "], + aliases: [alias], + tags: [_musicBrainzTagResponseFixture.Create(name: "Rock"), _musicBrainzTagResponseFixture.Create(name: "rock"), _musicBrainzTagResponseFixture.Create(name: " ")], + genres: [_musicBrainzTagResponseFixture.Create(name: "Pop"), _musicBrainzTagResponseFixture.Create(name: "POP")], + relations: + [ + _musicBrainzRelationResponseFixture.Create(type: "official homepage", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://artist.example")), + _musicBrainzRelationResponseFixture.Create(type: "official homepage", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://second.example")), + _musicBrainzRelationResponseFixture.Create(type: "wikidata", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://wikidata.example")), + _musicBrainzRelationResponseFixture.Create(type: "member of band", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "Member")), + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Producer")), + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Producer")), + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: " ")), + _musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "work") + ], + rating: _musicBrainzRatingResponseFixture.Create(value: 4.5m, votesCount: 12), + includeRating: true); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal("The Artist", result.Name); + Assert.Equal("Artist, The", result.SortName); + Assert.Equal("UK band", result.Disambiguation); + Assert.Equal(MusicArtistType.Group, result.Type); + Assert.Equal(MusicArtistGender.Female, result.Gender); + Assert.Equal("US", result.Country); + Assert.NotNull(result.Area); + Assert.Equal(areaId, result.Area.MusicBrainzAreaId); + Assert.Equal("United States", result.Area.Name); + Assert.Equal("United States", result.Area.SortName); + Assert.Equal("the country", result.Area.Disambiguation); + Assert.Equal("Country", result.Area.Type); + Assert.Equal("US", result.Area.Iso3166Code); + Assert.NotNull(result.BeginArea); + Assert.Equal(beginAreaId, result.BeginArea.MusicBrainzAreaId); + Assert.NotNull(result.EndArea); + Assert.Equal(endAreaId, result.EndArea.MusicBrainzAreaId); + Assert.Equal(new DateOnly(1950, 1, 1), result.LifeSpanBegin); + Assert.Equal(new DateOnly(2000, 12, 31), result.LifeSpanEnd); + Assert.True(result.IsEnded); + Assert.Equal("https://artist.example", result.Website); + Assert.Equal(artistId, result.MusicBrainzArtistId); + Assert.Equal(["IPI1"], result.Ipis); + Assert.Equal(["ISNI1"], result.Isnis); + MusicArtistAliasDto mappedAlias = Assert.Single(result.Aliases!); + Assert.Equal("The Alias", mappedAlias.Name); + Assert.Equal("Alias, The", mappedAlias.SortName); + Assert.Equal("Artist name", mappedAlias.Type); + Assert.Equal("en", mappedAlias.Locale); + Assert.True(mappedAlias.IsPrimary); + Assert.Equal(new DateOnly(1990, 1, 1), mappedAlias.BeginDate); + Assert.Equal(new DateOnly(2000, 1, 1), mappedAlias.EndDate); + Assert.False(mappedAlias.IsEnded); + Assert.Equal(["Rock"], result.Tags!.Select(tag => tag.Name)); + Assert.Equal(["Pop"], result.Genres!.Select(genre => genre.Name)); + Assert.Single(result.Ratings!); + Assert.Equal(4.5m, result.Ratings![0].Value); + Assert.Equal(5m, result.Ratings[0].MaxValue); + Assert.Equal(AudioRatingSource.MusicBrainz, result.Ratings[0].Source); + Assert.Equal(12, result.Ratings[0].VoteCount); + Assert.Equal(2, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Member" && contributor.Role == MediaContributorRole.Performer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Producer" && contributor.Role == MediaContributorRole.Producer); + } + + [Fact] + public void MapArtist_WhenOptionalFieldsAreMissing_ShouldReturnNullAndEmptyCollections() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + id: "not-a-guid", + name: " ", + includeSortName: false, + includeDisambiguation: false, + includeType: false, + includeGender: false, + includeCountry: false, + includeArea: false, + includeBeginArea: false, + includeEndArea: false, + includeLifeSpan: false, + isnis: [], + ipis: [], + aliases: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Null(result.Name); + Assert.Null(result.SortName); + Assert.Null(result.Disambiguation); + Assert.Null(result.Type); + Assert.Null(result.Gender); + Assert.Null(result.Country); + Assert.Null(result.Area); + Assert.Null(result.BeginArea); + Assert.Null(result.EndArea); + Assert.Null(result.LifeSpanBegin); + Assert.Null(result.LifeSpanEnd); + Assert.False(result.IsEnded); + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Empty(result.Ipis!); + Assert.Empty(result.Isnis!); + Assert.Empty(result.Aliases!); + Assert.Empty(result.Tags!); + Assert.Empty(result.Genres!); + Assert.Empty(result.Ratings!); + Assert.Empty(result.Contributors!); + } + + [Theory] + [InlineData("person", MusicArtistType.Person)] // an individual + [InlineData("group", MusicArtistType.Group)] // an ensemble + [InlineData("orchestra", MusicArtistType.Orchestra)] // an instrumental ensemble + [InlineData("choir", MusicArtistType.Choir)] // a vocal ensemble + [InlineData("character", MusicArtistType.Character)] // a fictional character + [InlineData("other", MusicArtistType.Other)] // a known but uncategorized type + [InlineData("PERSON", MusicArtistType.Person)] // the value is normalized + public void MapArtist_WhenTheTypeIsKnown_ShouldMapIt(string type, MusicArtistType expected) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create(type: type, relations: [], aliases: [], tags: [], genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(expected, result.Type); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapArtist_WhenTheTypeIsUnknown_ShouldReturnNullType(string? type) + { + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(_musicBrainzArtistResponseFixture.Create(type: type, includeType: type is not null, relations: [], aliases: [], tags: [], genres: [])); + + // Assert + Assert.Null(result.Type); + } + + [Theory] + [InlineData("male", MusicArtistGender.Male)] + [InlineData("female", MusicArtistGender.Female)] + [InlineData("other", MusicArtistGender.Other)] + [InlineData("not applicable", MusicArtistGender.NotApplicable)] + [InlineData("FEMALE", MusicArtistGender.Female)] // the value is normalized + public void MapArtist_WhenTheGenderIsKnown_ShouldMapIt(string gender, MusicArtistGender expected) + { + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(_musicBrainzArtistResponseFixture.Create(gender: gender, relations: [], aliases: [], tags: [], genres: [])); + + // Assert + Assert.Equal(expected, result.Gender); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("made-up")] + public void MapArtist_WhenTheGenderIsUnknown_ShouldReturnNullGender(string? gender) + { + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(_musicBrainzArtistResponseFixture.Create(gender: gender, includeGender: gender is not null, relations: [], aliases: [], tags: [], genres: [])); + + // Assert + Assert.Null(result.Gender); + } + + [Theory] + [InlineData("executive producer", MediaContributorRole.ExecutiveProducer)] // more specific than producer + [InlineData("producer", MediaContributorRole.Producer)] + [InlineData("remixer", MediaContributorRole.Remixer)] + [InlineData("mix", MediaContributorRole.Mixer)] + [InlineData("engineer", MediaContributorRole.Engineer)] + [InlineData("mastering", MediaContributorRole.Engineer)] + [InlineData("composer", MediaContributorRole.Composer)] + [InlineData("writer", MediaContributorRole.Author)] + [InlineData("lyricist", MediaContributorRole.Lyricist)] + [InlineData("librettist", MediaContributorRole.Lyricist)] + [InlineData("arranger", MediaContributorRole.Arranger)] + [InlineData("conductor", MediaContributorRole.Conductor)] + [InlineData("orchestrator", MediaContributorRole.Orchestrator)] + [InlineData("backing vocals", MediaContributorRole.BackingVocals)] + [InlineData("vocal", MediaContributorRole.Vocals)] + [InlineData("member of band", MediaContributorRole.Performer)] + [InlineData("performer", MediaContributorRole.Performer)] + [InlineData("orchestra", MediaContributorRole.Performer)] + [InlineData("choir", MediaContributorRole.Performer)] + [InlineData("made-up role", MediaContributorRole.Other)] + public void MapArtist_WhenAnArtistRelationHasAKnownType_ShouldMapTheRole(string relationType, MediaContributorRole expected) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: relationType, targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"))], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal(expected, contributor.Role); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void MapArtist_WhenAnArtistRelationHasNoType_ShouldMapTheRoleAsOther(string? relationType) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: relationType, includeType: relationType is not null, targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"))], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(MediaContributorRole.Other, Assert.Single(result.Contributors!).Role); + } + + [Theory] + [InlineData("backing vocal", MediaContributorRole.BackingVocals)] + [InlineData("vocals", MediaContributorRole.Vocals)] + [InlineData("bass guitar", MediaContributorRole.BassGuitar)] + [InlineData("guitar", MediaContributorRole.Guitar)] + [InlineData("drums", MediaContributorRole.Drums)] + [InlineData("percussion", MediaContributorRole.Percussion)] + [InlineData("keyboard", MediaContributorRole.Keyboards)] + [InlineData("piano", MediaContributorRole.Piano)] + [InlineData("synthesizer", MediaContributorRole.Synthesizer)] + [InlineData("synth", MediaContributorRole.Synthesizer)] + [InlineData("strings", MediaContributorRole.Strings)] + [InlineData("violin", MediaContributorRole.Strings)] + [InlineData("cello", MediaContributorRole.Strings)] + [InlineData("viola", MediaContributorRole.Strings)] + [InlineData("brass", MediaContributorRole.Brass)] + [InlineData("trumpet", MediaContributorRole.Brass)] + [InlineData("trombone", MediaContributorRole.Brass)] + [InlineData("horn", MediaContributorRole.Brass)] + [InlineData("woodwind", MediaContributorRole.Woodwinds)] + [InlineData("flute", MediaContributorRole.Woodwinds)] + [InlineData("saxophone", MediaContributorRole.Woodwinds)] + [InlineData("clarinet", MediaContributorRole.Woodwinds)] + public void MapArtist_WhenAnArtistRelationHasAnInstrumentAttribute_ShouldPreferTheInstrument(string attribute, MediaContributorRole expected) + { + // Arrange + // The relation type would map to a different role, so the instrument attribute must take precedence. + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"), attributes: [attribute])], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(expected, Assert.Single(result.Contributors!).Role); + } + + [Fact] + public void MapArtist_WhenAnArtistRelationHasAnUnknownInstrumentAttribute_ShouldFallBackToTheRelationType() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"), attributes: ["made-up instrument"])], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(MediaContributorRole.Producer, Assert.Single(result.Contributors!).Role); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void MapArtist_WhenAnArtistRelationHasABlankInstrumentAttribute_ShouldFallBackToTheRelationType(string attribute) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"), attributes: [attribute])], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(MediaContributorRole.Composer, Assert.Single(result.Contributors!).Role); + } + + [Fact] + public void MapArtist_WhenARelationTargetsAnotherType_ShouldIgnoreIt() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: + [ + _musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "work"), + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Producer")) + ], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Producer", contributor.Name!.DisplayName); + } + + [Fact] + public void MapArtist_WhenAnArtistRelationHasNoName_ShouldSkipIt() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: " "))], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Empty(result.Contributors!); + } + + [Fact] + public void MapArtist_WhenAUrlRelationIsNotAnOfficialHomepage_ShouldNotSetTheWebsite() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "wikidata", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://wikidata.example"))], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Null(result.Website); + } + + [Fact] + public void MapArea_WhenTheAreaIsNull_ShouldReturnNull() + { + // Act + MusicAreaDto? result = MusicBrainzMapper.MapArea(null); + + // Assert + Assert.Null(result); + } + + [Fact] + public void MapArea_WhenThePrimaryIsoCodeIsMissing_ShouldUseTheSecondaryIsoCode() + { + // Arrange + MusicBrainzAreaResponse area = _musicBrainzAreaResponseFixture.Create(id: Guid.NewGuid().ToString(), name: "Some Area", iso3166Part1Codes: [], iso3166Part2Codes: ["GB-ENG"]); + + // Act + MusicAreaDto? result = MusicBrainzMapper.MapArea(area); + + // Assert + Assert.NotNull(result); + Assert.Equal("GB-ENG", result.Iso3166Code); + } + + [Fact] + public void MapArea_WhenEveryOptionalFieldIsBlank_ShouldReturnNullFields() + { + // Arrange + MusicBrainzAreaResponse area = _musicBrainzAreaResponseFixture.Create(id: "not-a-guid", name: " ", includeSortName: false, includeDisambiguation: false, includeType: false, iso3166Part1Codes: [], iso3166Part2Codes: []); + + // Act + MusicAreaDto? result = MusicBrainzMapper.MapArea(area); + + // Assert + Assert.NotNull(result); + Assert.Null(result.MusicBrainzAreaId); + Assert.Null(result.Name); + Assert.Null(result.SortName); + Assert.Null(result.Disambiguation); + Assert.Null(result.Type); + Assert.Null(result.Iso3166Code); + } + + [Fact] + public void MapAlbum_WhenEveryFieldIsPresent_ShouldMapEveryField() + { + // Arrange + Guid releaseGroupId = Guid.NewGuid(); + Guid releaseId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + MusicBrainzArtistCreditResponse credit = _musicBrainzArtistCreditResponseFixture.Create(name: "The Album Artist", artist: _musicBrainzArtistResponseFixture.Create(id: releaseArtistId.ToString(), name: "The Album Artist"), includeJoinPhrase: false); + MusicBrainzMediumResponse medium = _musicBrainzMediumResponseFixture.Create(position: 1, format: "CD", tracks: [], trackCount: 12); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + id: releaseId.ToString(), + title: "The Release", + disambiguation: "remastered", + status: "Official", + date: "1995-11-21", + country: "US", + barcode: "1234567890123", + packaging: "Jewel Case", + textRepresentation: _musicBrainzTextRepresentationResponseFixture.Create(language: "eng", script: "Latn"), + artistCredit: [credit], + includeReleaseGroup: false, + labelInfo: + [ + _musicBrainzLabelInfoResponseFixture.Create(catalogNumber: "CAT-1", label: _musicBrainzLabelResponseFixture.Create(name: "The Label")), + _musicBrainzLabelInfoResponseFixture.Create(catalogNumber: "CAT-2", label: _musicBrainzLabelResponseFixture.Create(name: "Other Label")), + _musicBrainzLabelInfoResponseFixture.Create(catalogNumber: "cat-1", label: _musicBrainzLabelResponseFixture.Create(name: "Other Label")), + _musicBrainzLabelInfoResponseFixture.Create(catalogNumber: " ", label: _musicBrainzLabelResponseFixture.Create(name: "Other Label")) + ], + media: [medium, _musicBrainzMediumResponseFixture.Create(position: 2, format: "Vinyl", tracks: [], trackCount: 3)], + asin: "B000000001", + tags: [_musicBrainzTagResponseFixture.Create(name: "Rock")], + genres: [_musicBrainzTagResponseFixture.Create(name: "Pop")], + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Release Producer"))]); + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + id: releaseGroupId.ToString(), + title: "The Album", + disambiguation: "the album", + primaryType: "Album", + secondaryTypes: ["Live"], + firstReleaseDate: "1975-06-01", + artistCredit: [credit], + tags: [_musicBrainzTagResponseFixture.Create(name: "Rock"), _musicBrainzTagResponseFixture.Create(name: "rock")], + genres: [_musicBrainzTagResponseFixture.Create(name: "Pop")], + rating: _musicBrainzRatingResponseFixture.Create(value: 4m, votesCount: 8), + includeRating: true); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal("The Album", result.Title); + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Equal("the album", result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 6, 1), result.ReleaseInfo.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(new DateOnly(1995, 11, 21), result.ReleaseInfo.ReReleaseDate); + Assert.Equal(1995, result.ReleaseInfo.ReReleaseYear); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry); + Assert.Equal("remastered", result.ReleaseInfo.ReleaseVersion); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language.LanguageCode); + Assert.Null(result.OriginalLanguage); + Assert.Equal(["Rock"], result.Tags!.Select(tag => tag.Name)); + Assert.Equal(["Pop"], result.Genres!.Select(genre => genre.Name)); + Assert.Equal("Latn", result.Script); + Assert.Equal([MusicReleaseType.Album, MusicReleaseType.Live], result.ReleaseTypes); + Assert.Equal(MusicReleaseStatus.Official, result.ReleaseStatus); + Assert.Equal(MusicMediaFormat.CD, result.MediaFormat); + Assert.Equal(MusicReleasePackaging.JewelCase, result.Packaging); + Assert.Equal(2, result.TotalDiscs); + Assert.Equal(15, result.TotalTracks); + Assert.Equal("1234567890123", result.Barcode); + Assert.Equal(["CAT-1", "CAT-2"], result.CatalogNumbers); + Assert.Equal("The Label", result.Label); + Assert.Equal("B000000001", result.ASIN); + Assert.Equal(releaseId, result.MusicBrainzReleaseId); + Assert.Equal(releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal("The Release", result.ReleaseTitle); + Assert.Single(result.Ratings!); + Assert.Equal(4m, result.Ratings![0].Value); + Assert.Equal(2, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Album Artist" && contributor.Role == MediaContributorRole.Performer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Release Producer" && contributor.Role == MediaContributorRole.Producer); + } + + [Fact] + public void MapAlbum_WhenThereIsNoRelease_ShouldReturnNullReleaseLevelFields() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + id: Guid.NewGuid().ToString(), + title: "The Album", + includeDisambiguation: false, + includePrimaryType: false, + secondaryTypes: [], + includeFirstReleaseDate: false, + artistCredit: [], + tags: [], + genres: [], + includeRating: false); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Equal("The Album", result.Title); + Assert.Null(result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + Assert.Null(result.ReleaseInfo.ReleaseCountry); + Assert.Null(result.ReleaseInfo.ReleaseVersion); + Assert.Null(result.Language); + Assert.Empty(result.Tags!); + Assert.Empty(result.Genres!); + Assert.Null(result.Script); + Assert.Empty(result.ReleaseTypes!); + Assert.Null(result.ReleaseStatus); + Assert.Null(result.MediaFormat); + Assert.Null(result.Packaging); + Assert.Null(result.TotalDiscs); + Assert.Null(result.TotalTracks); + Assert.Null(result.Barcode); + Assert.Empty(result.CatalogNumbers!); + Assert.Null(result.Label); + Assert.Null(result.ASIN); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Equal(releaseGroup.Id, result.MusicBrainzReleaseGroupId.ToString()); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Empty(result.Contributors!); + Assert.Empty(result.Ratings!); + Assert.Null(result.ReleaseTitle); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupTitleIsBlank_ShouldFallBackToTheReleaseTitle() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(title: " ", artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(title: "The Release Title", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal("The Release Title", result.Title); + Assert.Equal("The Release Title", result.ReleaseTitle); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupCreditIsMissing_ShouldFallBackToTheReleaseCredit() + { + // Arrange + Guid releaseArtistId = Guid.NewGuid(); + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Release Artist", artist: _musicBrainzArtistResponseFixture.Create(id: releaseArtistId.ToString(), name: "Release Artist"))], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal("Release Artist", Assert.Single(result.Contributors!).Name!.DisplayName); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupCreditHasNoArtistId_ShouldFallBackToTheReleaseCreditId() + { + // Arrange + Guid releaseArtistId = Guid.NewGuid(); + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Group Artist", artist: _musicBrainzArtistResponseFixture.Create(id: null, includeId: false, name: "Group Artist"))], + tags: [], + genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Release Artist", artist: _musicBrainzArtistResponseFixture.Create(id: releaseArtistId.ToString(), name: "Release Artist"))], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + } + + [Fact] + public void MapAlbum_WhenTheReReleaseIsInTheSameYear_ShouldCollapseTheReRelease() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(firstReleaseDate: "1975-06-01", artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(date: "1975-11-21", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 6, 1), result.ReleaseInfo.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + } + + [Theory] + [InlineData("1975-11-21", 1975, 11, 21, 1975)] // an exact date is parsed fully + [InlineData("1975", null, 0, 0, 1975)] // a bare year yields only the year + [InlineData("Spring 1975", null, 0, 0, 1975)] // an embedded year is extracted when the value is not a date + [InlineData("not a date", null, 0, 0, null)] // an unparsable value yields nothing + [InlineData("2200", null, 0, 0, null)] // a year outside the accepted window yields nothing + [InlineData("2100", null, 0, 0, 2100)] // the upper boundary is accepted + [InlineData(" 1975-11-21 ", 1975, 11, 21, 1975)] // surrounding white space is trimmed + public void MapAlbum_WhenTheFirstReleaseDateHasVariousShapes_ShouldParseIt(string firstReleaseDate, int? expectedYear, int expectedMonth, int expectedDay, int? expectedParsedYear) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(firstReleaseDate: firstReleaseDate, artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.NotNull(result.ReleaseInfo); + if (expectedMonth == 0) + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); + else + Assert.Equal(new DateOnly(expectedYear!.Value, expectedMonth, expectedDay), result.ReleaseInfo.OriginalReleaseDate); + Assert.Equal(expectedParsedYear, result.ReleaseInfo.OriginalReleaseYear); + } + + [Theory] + [InlineData("US", ReleaseCountry.US)] + [InlineData("us", ReleaseCountry.US)] // the code is matched case insensitively + [InlineData("XE", ReleaseCountry.XE)] // the Europe special code + [InlineData("XW", ReleaseCountry.XW)] // the Worldwide special code + [InlineData("AN", ReleaseCountry.AN)] // the Netherlands Antilles special code + public void MapAlbum_WhenTheReleaseCountryIsKnown_ShouldMapIt(string country, ReleaseCountry expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(country: country, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(expected, result.ReleaseInfo!.ReleaseCountry); + } + + [Theory] + [InlineData("ZZ")] // a valid shape but not a known code + [InlineData("")] // an empty value + [InlineData(" ")] // only white space + public void MapAlbum_WhenTheReleaseCountryIsUnknown_ShouldReturnNullCountry(string country) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(country: country, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.ReleaseInfo!.ReleaseCountry); + } + + [Theory] + [InlineData("album", MusicReleaseType.Album)] + [InlineData("single", MusicReleaseType.Single)] + [InlineData("ep", MusicReleaseType.Ep)] + [InlineData("broadcast", MusicReleaseType.Broadcast)] + [InlineData("other", MusicReleaseType.Other)] + [InlineData("compilation", MusicReleaseType.Compilation)] + [InlineData("live", MusicReleaseType.Live)] + [InlineData("soundtrack", MusicReleaseType.Soundtrack)] + [InlineData("spokenword", MusicReleaseType.SpokenWord)] + [InlineData("audio drama", MusicReleaseType.AudioDrama)] + [InlineData("audiobook", MusicReleaseType.AudioBook)] + [InlineData("demo", MusicReleaseType.Demo)] + [InlineData("dj-mix", MusicReleaseType.DjMix)] + [InlineData("field recording", MusicReleaseType.FieldRecording)] + [InlineData("interview", MusicReleaseType.Interview)] + [InlineData("mixtape/street", MusicReleaseType.Mixtape)] + [InlineData("remix", MusicReleaseType.Remix)] + public void MapAlbum_WhenThePrimaryReleaseTypeIsKnown_ShouldMapIt(string primaryType, MusicReleaseType expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(primaryType: primaryType, secondaryTypes: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Equal([expected], result.ReleaseTypes); + } + + [Fact] + public void MapAlbum_WhenTheReleaseTypesContainDuplicatesAndUnknowns_ShouldKeepOnlyTheDistinctKnownOnes() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(primaryType: "Album", secondaryTypes: ["Live", "live", "made-up", "Album"], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Equal([MusicReleaseType.Album, MusicReleaseType.Live], result.ReleaseTypes); + } + + [Theory] + [InlineData("official", MusicReleaseStatus.Official)] + [InlineData("promotion", MusicReleaseStatus.Promotion)] + [InlineData("bootleg", MusicReleaseStatus.Bootleg)] + [InlineData("pseudo-release", MusicReleaseStatus.PseudoRelease)] + [InlineData("withdrawn", MusicReleaseStatus.Withdrawn)] + [InlineData("cancelled", MusicReleaseStatus.Cancelled)] + [InlineData("expunged", MusicReleaseStatus.Expunged)] + public void MapAlbum_WhenTheReleaseStatusIsKnown_ShouldMapIt(string status, MusicReleaseStatus expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(status: status, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(expected, result.ReleaseStatus); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapAlbum_WhenTheReleaseStatusIsUnknown_ShouldReturnNullStatus(string? status) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(status: status, includeStatus: status is not null, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.ReleaseStatus); + } + + [Theory] + [InlineData("cd", MusicMediaFormat.CD)] + [InlineData("vinyl", MusicMediaFormat.Vinyl)] + [InlineData("12\" vinyl", MusicMediaFormat.Inch12Vinyl)] + [InlineData("10\" vinyl", MusicMediaFormat.Inch10Vinyl)] + [InlineData("7\" vinyl", MusicMediaFormat.Inch7Vinyl)] + [InlineData("digital media", MusicMediaFormat.DigitalMedia)] + [InlineData("cassette", MusicMediaFormat.Cassette)] + [InlineData("dvd", MusicMediaFormat.DVD)] + [InlineData("dvd-video", MusicMediaFormat.DVDVideo)] + [InlineData("dvd-audio", MusicMediaFormat.DVDAudio)] + [InlineData("sacd", MusicMediaFormat.SACD)] + [InlineData("hybrid sacd", MusicMediaFormat.HybridSACD)] + [InlineData("blu-ray", MusicMediaFormat.BluRay)] + [InlineData("minidisc", MusicMediaFormat.MiniDisc)] + [InlineData("8cm cd", MusicMediaFormat.Cm8CD)] + [InlineData("dat", MusicMediaFormat.DAT)] + [InlineData("other", MusicMediaFormat.Other)] + [InlineData("made-up", MusicMediaFormat.Other)] // an unknown format still maps to Other + public void MapAlbum_WhenTheMediaFormatIsKnownOrUnknownButPresent_ShouldMapIt(string format, MusicMediaFormat expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + media: [_musicBrainzMediumResponseFixture.Create(position: 1, format: format, tracks: [], trackCount: 0)], + includeReleaseGroup: false, + includeTextRepresentation: false, + labelInfo: [], + artistCredit: [], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(expected, result.MediaFormat); + } + + [Theory] + [InlineData("book", MusicReleasePackaging.Book)] + [InlineData("box", MusicReleasePackaging.Box)] + [InlineData("cardboard/paper sleeve", MusicReleasePackaging.CardboardPaperSleeve)] + [InlineData("cassette case", MusicReleasePackaging.CassetteCase)] + [InlineData("clamshell case", MusicReleasePackaging.ClamshellCase)] + [InlineData("digibook", MusicReleasePackaging.Digibook)] + [InlineData("digifile", MusicReleasePackaging.Digifile)] + [InlineData("digipak", MusicReleasePackaging.Digipak)] + [InlineData("discbox slider", MusicReleasePackaging.DiscboxSlider)] + [InlineData("fatbox", MusicReleasePackaging.Fatbox)] + [InlineData("gatefold cover", MusicReleasePackaging.GatefoldCover)] + [InlineData("jewel case", MusicReleasePackaging.JewelCase)] + [InlineData("keep case", MusicReleasePackaging.KeepCase)] + [InlineData("longbox", MusicReleasePackaging.Longbox)] + [InlineData("metal tin", MusicReleasePackaging.MetalTin)] + [InlineData("plastic sleeve", MusicReleasePackaging.PlasticSleeve)] + [InlineData("slidepack", MusicReleasePackaging.Slidepack)] + [InlineData("slim jewel case", MusicReleasePackaging.SlimJewelCase)] + [InlineData("slipcase", MusicReleasePackaging.Slipcase)] + [InlineData("snap case", MusicReleasePackaging.SnapCase)] + [InlineData("snappack", MusicReleasePackaging.SnapPack)] + [InlineData("super jewel box", MusicReleasePackaging.SuperJewelBox)] + [InlineData("none", MusicReleasePackaging.None)] + [InlineData("other", MusicReleasePackaging.Other)] + [InlineData("made-up", MusicReleasePackaging.Other)] // an unknown packaging still maps to Other + public void MapAlbum_WhenThePackagingIsKnownOrUnknownButPresent_ShouldMapIt(string packaging, MusicReleasePackaging expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(packaging: packaging, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(expected, result.Packaging); + } + + [Fact] + public void MapAlbum_WhenTheMediaAreMissing_ShouldReturnNullDiscAndTrackCounts() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(media: [], includeReleaseGroup: false, includeTextRepresentation: false, labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.TotalDiscs); + Assert.Null(result.TotalTracks); + } + + [Fact] + public void MapAlbum_WhenTheMediaFormatIsBlank_ShouldReturnNullMediaFormat() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + media: [_musicBrainzMediumResponseFixture.Create(position: 1, format: " ", tracks: [], trackCount: 0)], + includeReleaseGroup: false, + includeTextRepresentation: false, + labelInfo: [], + artistCredit: [], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.MediaFormat); + } + + [Fact] + public void MapAlbum_WhenThePackagingIsBlank_ShouldReturnNullPackaging() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(packaging: " ", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.Packaging); + } + + [Fact] + public void MapTrack_WhenEveryFieldIsPresent_ShouldMapEveryField() + { + // Arrange + Guid recordingId = Guid.NewGuid(); + Guid workId = Guid.NewGuid(); + MusicBrainzWorkResponse work = _musicBrainzWorkResponseFixture.Create( + id: workId.ToString(), + title: "The Work", + type: "Song", + disambiguation: "the work", + languages: ["eng"], + iswcs: ["T-010.154.482-4"], + relations: [_musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Work Composer"))], + tags: [], + genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + date: "1975-11-21", + textRepresentation: _musicBrainzTextRepresentationResponseFixture.Create(language: "eng", script: "Latn"), + includeReleaseGroup: false, + media: [], + labelInfo: [], + artistCredit: [], + tags: [], + genres: []); + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: recordingId.ToString(), + title: " The Track ", + disambiguation: "the track", + length: 215_400, + isVideo: true, + firstReleaseDate: "1975-10-31", + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "The Track Artist", includeJoinPhrase: false)], + isrcs: ["US1A2B3C4D5E", "", " "], + releases: [], + tags: [_musicBrainzTagResponseFixture.Create(name: "Rock")], + genres: [_musicBrainzTagResponseFixture.Create(name: "Pop")], + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Producer"))], + rating: _musicBrainzRatingResponseFixture.Create(value: 3m, votesCount: 4), + includeRating: true); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, work, release); + + // Assert + Assert.Equal("The Track", result.Title); + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Equal("the track", result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 10, 31), result.ReleaseInfo.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + Assert.Null(result.ReleaseInfo.ReleaseCountry); + Assert.Null(result.ReleaseInfo.ReleaseVersion); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language.LanguageCode); + Assert.Null(result.OriginalLanguage); + Assert.Equal(["Rock"], result.Tags!.Select(tag => tag.Name)); + Assert.Equal(["Pop"], result.Genres!.Select(genre => genre.Name)); + Assert.Equal("Latn", result.Script); + Assert.Null(result.Key); + Assert.Null(result.Bpm); + Assert.True(result.IsVideo); + Assert.NotNull(result.Work); + Assert.Equal(workId, result.Work.MusicBrainzWorkId); + Assert.Equal("The Work", result.Work.Title); + Assert.Equal("Song", result.Work.Type); + Assert.Equal("en", Assert.Single(result.Work.Languages!).LanguageCode); + Assert.Equal("T-010.154.482-4", Assert.Single(result.Work.Iswcs!)); + Assert.Equal("US1A2B3C4D5E", Assert.Single(result.Isrcs!).Value); + Assert.Null(result.Moods); + Assert.Equal(215, result.DurationInSeconds); + Assert.Null(result.SampleRate); + Assert.Null(result.Channels); + Assert.Null(result.BitDepth); + Assert.Null(result.AudioCodec); + Assert.Null(result.Bitrate); + Assert.Equal(recordingId, result.MusicBrainzRecordingId); + Assert.Null(result.MusicBrainzTrackId); + Assert.Single(result.Ratings!); + Assert.Equal(3m, result.Ratings![0].Value); + Assert.Equal(4, result.Ratings[0].VoteCount); + Assert.Equal(3, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Track Artist" && contributor.Role == MediaContributorRole.Performer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Producer" && contributor.Role == MediaContributorRole.Producer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Work Composer" && contributor.Role == MediaContributorRole.Composer); + } + + [Fact] + public void MapTrack_WhenTheRecordingHasNoFirstReleaseDate_ShouldFallBackToTheReleaseDate() + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + includeFirstReleaseDate: false, + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(date: "1975-10-31", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, release); + + // Assert + Assert.Equal(new DateOnly(1975, 10, 31), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + } + + [Fact] + public void MapTrack_WhenTheRecordingHasAFirstReleaseDate_ShouldPreferItOverTheReleaseDate() + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + firstReleaseDate: "1975-11-21", + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(date: "2011-03-14", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, release); + + // Assert + Assert.Equal(new DateOnly(1975, 11, 21), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + } + + [Theory] + [InlineData(null, null)] // no length at all + [InlineData(0L, null)] // a zero length is treated as unknown + [InlineData(-100L, null)] // a negative length is treated as unknown + [InlineData(1500L, 1)] // milliseconds are truncated to whole seconds + [InlineData(215_400L, 215)] + public void MapTrack_WhenTheRecordingHasALength_ShouldMapTheDurationInSeconds(long? length, int? expectedSeconds) + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + length: length, + includeLength: length is not null, + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, null); + + // Assert + Assert.Equal(expectedSeconds, result.DurationInSeconds); + } + + [Fact] + public void MapTrack_WhenTheVideoFlagIsMissing_ShouldReturnFalse() + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + includeVideo: false, + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, null); + + // Assert + Assert.False(result.IsVideo); + } + + [Fact] + public void MapTrack_WhenTheOptionalCollectionsAreEmpty_ShouldReturnNullWorkAndEmptyCollections() + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: "not-a-guid", + title: " ", + includeDisambiguation: false, + includeLength: false, + includeVideo: false, + includeFirstReleaseDate: false, + artistCredit: [], + isrcs: [], + releases: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, null); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.Language); + Assert.Empty(result.Tags!); + Assert.Empty(result.Genres!); + Assert.Null(result.Script); + Assert.Null(result.Work); + Assert.Empty(result.Isrcs!); + Assert.Null(result.DurationInSeconds); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Empty(result.Contributors!); + Assert.Empty(result.Ratings!); + } + + [Theory] + [InlineData(1.0)] // a value only + [InlineData(2.5)] + public void MapArtist_WhenOnlyTheRatingValueIsPresent_ShouldMapItWithANullVoteCount(decimal value) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [], + aliases: [], + tags: [], + genres: [], + rating: _musicBrainzRatingResponseFixture.Create(value: value, includeVotesCount: false), + includeRating: true); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + AudioRatingDto rating = Assert.Single(result.Ratings!); + Assert.Equal(value, rating.Value); + Assert.Null(rating.VoteCount); + } + + [Fact] + public void MapArtist_WhenOnlyTheRatingVoteCountIsPresent_ShouldMapItWithANullValue() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [], + aliases: [], + tags: [], + genres: [], + rating: _musicBrainzRatingResponseFixture.Create(includeValue: false, votesCount: 7), + includeRating: true); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + AudioRatingDto rating = Assert.Single(result.Ratings!); + Assert.Null(rating.Value); + Assert.Equal(7, rating.VoteCount); + } + + [Fact] + public void MapArtist_WhenTheRatingHasNoValueNorVotes_ShouldReturnAnEmptyRatingList() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [], + aliases: [], + tags: [], + genres: [], + rating: _musicBrainzRatingResponseFixture.Create(includeValue: false, includeVotesCount: false), + includeRating: true); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Empty(result.Ratings!); + } + + [Theory] + [InlineData("eng", "en", "English")] // a three letter code maps to the neutral culture + [InlineData("deu", "de", "German")] + [InlineData("en", "en", "English")] // a two letter code maps too + [InlineData("zxx", "zxx", "No linguistic content")] // a special MusicBrainz code + [InlineData("mul", "mul", "Multiple languages")] + [InlineData("und", "und", "Undetermined")] + [InlineData("eng/ara", "en", "English")] // only the first code of a multi language value is used + [InlineData("/", "/", "/")] // a value with no usable part falls back to the raw code + [InlineData(" eng ", "en", "English")] // surrounding white space is trimmed + [InlineData("qqq", "qqq", "qqq")] // an unknown code falls back to the raw code + public void MapTrack_WhenTheLanguageCodeIsPresent_ShouldMapIt(string language, string expectedCode, string expectedName) + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + textRepresentation: _musicBrainzTextRepresentationResponseFixture.Create(language: language, includeScript: false), + includeReleaseGroup: false, + media: [], + labelInfo: [], + artistCredit: [], + tags: [], + genres: []); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, release); + + // Assert + Assert.NotNull(result.Language); + Assert.Equal(expectedCode, result.Language.LanguageCode); + Assert.Equal(expectedName, result.Language.LanguageName); + } + + [Fact] + public void MapWork_WhenEveryFieldIsPresent_ShouldMapEveryField() + { + // Arrange + Guid workId = Guid.NewGuid(); + MusicBrainzWorkResponse work = _musicBrainzWorkResponseFixture.Create( + id: workId.ToString(), + title: " The Work ", + type: "Song", + languages: ["eng", "zxx", ""], + iswcs: ["T-1", " ", "T-2"]); + + // Act + MusicWorkDto result = MusicBrainzMapper.MapWork(work); + + // Assert + Assert.Equal(workId, result.MusicBrainzWorkId); + Assert.Equal("The Work", result.Title); + Assert.Equal("Song", result.Type); + Assert.Equal(2, result.Languages!.Count); + Assert.Equal("en", result.Languages[0].LanguageCode); + Assert.Equal("zxx", result.Languages[1].LanguageCode); + Assert.Equal(["T-1", "T-2"], result.Iswcs); + } + + [Fact] + public void MapWork_WhenTheIdentifierIsNotAGuid_ShouldReturnNullIdentifier() + { + // Arrange + MusicBrainzWorkResponse work = _musicBrainzWorkResponseFixture.Create(id: "not-a-guid", includeTitle: false, includeType: false, languages: [], iswcs: []); + + // Act + MusicWorkDto result = MusicBrainzMapper.MapWork(work); + + // Assert + Assert.Null(result.MusicBrainzWorkId); + Assert.Null(result.Title); + Assert.Null(result.Type); + Assert.Empty(result.Languages!); + Assert.Empty(result.Iswcs!); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupCreditsHaveNoUsableName_ShouldFallBackToTheReleaseCredits() + { + // Arrange + Guid releaseArtistId = Guid.NewGuid(); + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: null, includeName: false, includeArtist: false)], + tags: [], + genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Release Artist", artist: _musicBrainzArtistResponseFixture.Create(id: releaseArtistId.ToString(), name: "Release Artist"))], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal("Release Artist", Assert.Single(result.Contributors!).Name!.DisplayName); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupCreditHasNoNameButItsArtistDoes_ShouldFallBackToTheArtistName() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: null, includeName: false, artist: _musicBrainzArtistResponseFixture.Create(name: "The Artist"))], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Equal("The Artist", Assert.Single(result.Contributors!).Name!.DisplayName); + } + + [Fact] + public void MapAlbum_WhenAReleaseRelationTargetsAnArtistWithoutAName_ShouldSkipIt() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "The Artist", includeJoinPhrase: false)], + tags: [], + genres: [], + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: false)]); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Artist", contributor.Name!.DisplayName); + } + + [Fact] + public void MapArtist_WhenAUrlRelationPrecedesAnOfficialHomepage_ShouldPreferTheOfficialHomepage() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: + [ + _musicBrainzRelationResponseFixture.Create(type: "wikidata", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://wikidata.example")), + _musicBrainzRelationResponseFixture.Create(type: "official homepage", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://artist.example")) + ], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal("https://artist.example", result.Website); + } + + [Fact] + public void MapArtist_WhenAnArtistRelationHasNoArtist_ShouldSkipIt() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: false)], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Empty(result.Contributors!); + } + + [Fact] + public void MapArtist_WhenTheSameNameIsCreditedWithTwoRoles_ShouldKeepBothContributors() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: + [ + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person")), + _musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person")) + ], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + } + + [Fact] + public void MapAlbum_WhenNeitherCreditHasAnArtistIdentifier_ShouldReturnNullReleaseArtistId() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Group Artist", includeArtist: false)], + tags: [], + genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Release Artist", includeArtist: false)], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.MusicBrainzReleaseArtistId); + } + + [Fact] + public void MapAlbum_WhenTheReleaseIsNullAndTheCreditHasNoArtistIdentifier_ShouldReturnNullReleaseArtistId() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Group Artist", includeArtist: false)], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Null(result.MusicBrainzReleaseArtistId); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzAlbumMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzAlbumMetadataProviderTests.cs new file mode 100644 index 00000000..817b050a --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzAlbumMetadataProviderTests.cs @@ -0,0 +1,592 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzAlbumMetadataProviderTests +{ + private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid s_releaseGroupId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("MusicBrainz", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnTrue() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task GetSearchResultsAsync_WhenTheTitleIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? title) + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: title); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheSearchReturnsReleaseGroups_ShouldMapEveryTitledOneAndSkipTheUntitledOnes() + { + // Arrange + const string SEARCH_JSON = """ + { + "count": 3, + "release-groups": [ + { "id": "22222222-2222-2222-2222-222222222222", "title": "The Album", "primary-type": "Album" }, + { "id": "33333333-3333-3333-3333-333333333333", "title": "Other Album" }, + { "id": "44444444-4444-4444-4444-444444444444", "title": null } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: " The \"Album\" ", artistName: " The Artist "); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal("The Album", result[0].Title); + Assert.Equal("Other Album", result[1].Title); + Assert.Equal(1, handler.CallCount); + Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query); + // the quotes are removed from the built query, and the artist constraint is appended + string query = Uri.UnescapeDataString(handler.Requests[0].RequestUri!.Query); + Assert.Contains("releasegroup:\"The Album\"", query); + Assert.Contains("AND artist:\"The Artist\"", query); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseAndTheArtistArePresent_ShouldMapBothTheReleaseGroupAndTheRelease() + { + // Arrange + string releaseJson = ReleaseJson(s_releaseId, "The Release", s_releaseGroupId, "The Album", "1975-06-01", "Official", "1975-11-21", "US"); + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : releaseJson)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Album", result.Title); + Assert.Equal(s_releaseId, result.MusicBrainzReleaseId); + Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal("The Release", result.ReleaseTitle); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseIdentifierIsPresentButTheReleaseIsNotFound_ShouldReturnNull() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseCarriesAnUnparsableReleaseGroupIdentifier_ShouldMapOnlyTheRelease() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "release-group": { "id": "not-a-guid", "title": "The Album" } + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Release", result.Title); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseDoesNotReferenceAReleaseGroup_ShouldMapOnlyTheRelease() + { + // Arrange + const string RELEASE_JSON = """{"id":"11111111-1111-1111-1111-111111111111","title":"The Release"}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Release", result.Title); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenThereIsNeitherAnIdentifierNorATitle_ShouldReturnNullWithoutAnyRequest() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: " "); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenOnlyTheTitleIsPresent_ShouldSearchAndResolveTheFirstReleaseGroup() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"The Album"}]}"""; + const string BROWSE_JSON = """{"release-count":0,"releases":[]}"""; + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(Route(request, SEARCH_JSON, releaseGroupJson, BROWSE_JSON))); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album"); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Album", result.Title); + Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId); + // the search, the detail lookup and the release browse are all used + Assert.Equal(3, handler.CallCount); + Assert.Contains("limit=1", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTitleSearchReturnsNothing_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":0,"release-groups":[]}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album"); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsNotAGuid_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"not-a-guid","title":"The Album"}]}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album"); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseGroupIdentifierIsPresent_ShouldFetchItDirectly() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseGroupJson)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Contains($"/release-group/{s_releaseGroupId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseGroupIsUnknownButATitleIsPresent_ShouldFallBackToTheTitleSearch() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"The Album"}]}"""; + const string BROWSE_JSON = """{"release-count":0,"releases":[]}"""; + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.Query.Contains("query=") + ? Json(SEARCH_JSON) + : request.RequestUri.AbsolutePath.Contains("/release-group/") + ? callIndex == 1 + ? new HttpResponseMessage(HttpStatusCode.NotFound) + : Json(releaseGroupJson) + : Json(BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, title: "The Album"); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Album", result.Title); + Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(4, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseGroupIdentifierIsPresentButTheDetailIsMissing_ShouldReturnNull() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheLocalTrackCountIsUnknown_ShouldNotSelectAnyRelease() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseGroupJson)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: null); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenNoReleaseMatchesTheLocalTrackCount_ShouldNotSelectAnyRelease() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"The Release","media":[{"position":1,"track-count":9}]}]}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 12); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenSeveralReleasesMatch_ShouldSelectTheBestScoredOne() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """ + { + "release-count": 3, + "releases": [ + { "id": "11111111-1111-1111-1111-111111111111", "title": "Bootleg Edition", "status": "Bootleg", "date": "1975", "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "22222222-2222-2222-2222-222222222222", "title": "Official Edition", "status": "Official", "date": "1975-11-21", "barcode": "123", "label-info": [ { "catalog-number": "CAT" } ], "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "33333333-3333-3333-3333-333333333333", "title": "Promotion Edition", "status": "Promotion", "date": "1980-01-01", "media": [ { "position": 1, "track-count": 2 } ] } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("22222222-2222-2222-2222-222222222222"), result.MusicBrainzReleaseId); + Assert.Equal("Official Edition", result.ReleaseTitle); + } + + [Fact] + public async Task GetMetadataAsync_WhenSeveralReleasesScoreTheSame_ShouldSelectTheFirstOne() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """ + { + "release-count": 2, + "releases": [ + { "id": "11111111-1111-1111-1111-111111111111", "title": "First Edition", "status": "Official", "date": "1975-11-21", "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "22222222-2222-2222-2222-222222222222", "title": "Second Edition", "status": "Official", "date": "1975-11-21", "media": [ { "position": 1, "track-count": 2 } ] } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseDateIsUnparsable_ShouldStillSelectTheMatchingRelease() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """ + { + "release-count": 2, + "releases": [ + { "id": "11111111-1111-1111-1111-111111111111", "title": "Unparsable Edition", "status": "Official", "date": "not a date", "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "22222222-2222-2222-2222-222222222222", "title": "Matching Edition", "status": "Official", "date": "1975-06-01", "media": [ { "position": 1, "track-count": 2 } ] } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("22222222-2222-2222-2222-222222222222"), result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseCarriesSeveralCatalogNumbers_ShouldMapAllOfThem() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "A Night at the Opera", + "release-group": { "id": "22222222-2222-2222-2222-222222222222", "title": "A Night at the Opera", "primary-type": "Album" }, + "label-info": [ + { "catalog-number": "EMC 4008", "label": { "name": "EMI" } }, + { "catalog-number": "0C 066-98 485", "label": { "name": "EMI" } }, + { "catalog-number": "EMC 4008", "label": { "name": "EMI" } } + ] + } + """; + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "A Night at the Opera", "Album", "1975-11-21"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : RELEASE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.CatalogNumbers); + // every distinct catalog number is kept, while the duplicates are removed. + Assert.Equal(["EMC 4008", "0C 066-98 485"], result.CatalogNumbers); + Assert.Equal("EMI", result.Label); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheMatchingReleaseHasNoMedia_ShouldStillSelectIt() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"Empty Edition","status":"Official","media":[]}]}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 0); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseDatesAreMissingOrTooShort_ShouldStillSelectAMatchingRelease() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """ + { + "release-count": 2, + "releases": [ + { "id": "11111111-1111-1111-1111-111111111111", "status": "Official", "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "22222222-2222-2222-2222-222222222222", "status": "Official", "date": "75", "media": [ { "position": 1, "track-count": 2 } ] } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId); + } + + /// + /// Creates a whose requests are answered by the provided stub handler. + /// + /// The factory that produces the response of a request. + /// The created provider and its stub handler. + private (MusicBrainzAlbumMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func responseFactory) + { + StubHttpMessageHandler handler = new(responseFactory); + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: "http://localhost/", + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.Zero)); + MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + return (new MusicBrainzAlbumMetadataProvider(httpClient, settingsProvider), handler); + } + + /// + /// Routes a request to the search, release group or release browse JSON, based on the request URI. + /// + /// The request to route. + /// The JSON returned for a search request. + /// The JSON returned for a release group detail request. + /// The JSON returned for a release browse request. + /// The JSON that answers the request. + private static string Route(HttpRequestMessage request, string searchString, string releaseGroupJson, string browseJson) + { + if (request.RequestUri!.Query.Contains("query=", StringComparison.Ordinal)) + return searchString; + return request.RequestUri.AbsolutePath.Contains("/release-group/", StringComparison.Ordinal) ? releaseGroupJson : browseJson; + } + + /// + /// Creates the JSON of a release group response. + /// + /// The MusicBrainz identifier of the release group. + /// The title of the release group. + /// The primary type of the release group. + /// The first release date of the release group. + /// The JSON of the release group response. + private static string ReleaseGroupJson(Guid id, string title, string primaryType, string firstReleaseDate) + { + return $$"""{"id":"{{id:D}}","title":"{{title}}","primary-type":"{{primaryType}}","first-release-date":"{{firstReleaseDate}}"}"""; + } + + /// + /// Creates the JSON of a release response. + /// + /// The MusicBrainz identifier of the release. + /// The title of the release. + /// The MusicBrainz identifier of the release group. + /// The title of the release group. + /// The first release date of the release group. + /// The date the release was issued. + /// The status of the release. + /// The date of the release. + /// The country the release was issued in. + /// The JSON of the release response. + private static string ReleaseJson(Guid id, string title, Guid releaseGroupId, string releaseGroupTitle, string releaseGroupFirstReleaseDate, string status, string releaseDate, string country) + { + return $$""" + { + "id": "{{id:D}}", + "title": "{{title}}", + "status": "{{status}}", + "date": "{{releaseDate}}", + "country": "{{country}}", + "release-group": { "id": "{{releaseGroupId:D}}", "title": "{{releaseGroupTitle}}", "primary-type": "Album", "first-release-date": "{{releaseGroupFirstReleaseDate}}" } + } + """; + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzArtistMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzArtistMetadataProviderTests.cs new file mode 100644 index 00000000..514babe0 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzArtistMetadataProviderTests.cs @@ -0,0 +1,308 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzArtistMetadataProviderTests +{ + private static readonly Guid s_artistId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + + private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new(); + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("MusicBrainz", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnTrue() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task GetSearchResultsAsync_WhenTheNameIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? name) + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: name); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheSearchReturnsArtists_ShouldMapEveryNamedArtistAndSkipTheUnnamedOnes() + { + // Arrange + const string SEARCH_JSON = """ + { + "count": 3, + "artists": [ + { "id": "11111111-1111-1111-1111-111111111111", "name": "The Artist" }, + { "id": "22222222-2222-2222-2222-222222222222", "name": "Other Artist" }, + { "id": "33333333-3333-3333-3333-333333333333", "name": null } + ] + } + """; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: " The Artist "); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal("The Artist", result[0].Name); + Assert.Equal("Other Artist", result[1].Name); + Assert.Equal(1, handler.CallCount); + // the name is trimmed and the configured search result limit is used + Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query); + Assert.Contains("query=The%20Artist", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheSearchResponseIsEmpty_ShouldReturnAnEmptyCollection() + { + // Arrange + const string SEARCH_JSON = """{"count":0,"artists":[]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheMusicBrainzIdentifierIsPresent_ShouldLookUpTheArtistByIdentifier() + { + // Arrange + string artistJson = CreateArtistJson("The Artist", "Group", "11111111-1111-1111-1111-111111111111"); + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(artistJson)); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", musicBrainzArtistId: s_artistId); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Artist", result.Name); + Assert.Equal(MusicArtistType.Group, result.Type); + Assert.Equal(s_artistId, result.MusicBrainzArtistId); + Assert.Equal(1, handler.CallCount); + Assert.Contains($"/artist/{s_artistId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheIdentifierLookupReturnsNothing_ShouldReturnNull() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", musicBrainzArtistId: s_artistId); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenThereIsNeitherAnIdentifierNorAName_ShouldReturnNullWithoutAnyRequest() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: " "); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheNameSearchReturnsNothing_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":0,"artists":[]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchResultHasNoIdentifier_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":null,"name":"The Artist"}]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsNotAGuid_ShouldMapTheSearchResult() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":"not-a-guid","name":"The Artist","type":"Group"}]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Artist", result.Name); + Assert.Equal(MusicArtistType.Group, result.Type); + Assert.Null(result.MusicBrainzArtistId); + // the search is used, and the per identifier lookup must not be requested + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsAGuid_ShouldResolveTheDetailedArtist() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":"11111111-1111-1111-1111-111111111111","name":"The Artist"}]}"""; + string detailJson = CreateArtistJson("The Detailed Artist", "Person", "11111111-1111-1111-1111-111111111111"); + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => request.RequestUri!.AbsolutePath.Contains("/artist/") ? Json(detailJson) : Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Detailed Artist", result.Name); + Assert.Equal(MusicArtistType.Person, result.Type); + Assert.Equal(2, handler.CallCount); + Assert.Contains("limit=1", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheDetailedArtistLookupReturnsNothing_ShouldMapTheSearchResult() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":"11111111-1111-1111-1111-111111111111","name":"The Artist","type":"Group"}]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => request.RequestUri!.AbsolutePath.Contains("/artist/") ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Artist", result.Name); + Assert.Equal(MusicArtistType.Group, result.Type); + Assert.Equal(2, handler.CallCount); + } + + /// + /// Creates a whose requests are answered by the provided stub handler. + /// + /// The factory that produces the response of a request. + /// The created provider and its stub handler. + private (MusicBrainzArtistMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func responseFactory) + { + StubHttpMessageHandler handler = new(responseFactory); + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: "http://localhost/", + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.Zero)); + MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + return (new MusicBrainzArtistMetadataProvider(httpClient, settingsProvider), handler); + } + + /// + /// Creates the JSON of an artist response. + /// + /// The name of the artist. + /// The MusicBrainz type of the artist. + /// The MusicBrainz identifier of the artist. + /// The JSON of the artist response. + private static string CreateArtistJson(string name, string type, string id) + { + return $$"""{"id":"{{id}}","name":"{{name}}","type":"{{type}}"}"""; + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzPluginTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzPluginTests.cs new file mode 100644 index 00000000..df7b9157 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzPluginTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzPluginTests +{ + private readonly MusicBrainzPlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(MusicBrainzPlugin.s_pluginId, result); + Assert.Equal(new Guid("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("MusicBrainz Metadata", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Retrieves artist, album and track metadata from MusicBrainz.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnTheSixSettingDescriptors() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Equal(6, result.Count); + Assert.Equal( + [ + MusicBrainzSettingsKeys.BASE_URL, + MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, + MusicBrainzSettingsKeys.CONTACT_EMAIL, + MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, + MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, + MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS + ], + result.Select(descriptor => descriptor.Key)); + } + + [Theory] + [InlineData(MusicBrainzSettingsKeys.BASE_URL, "Base URL", PluginSettingType.Text, "https://musicbrainz.org/ws/2/")] + [InlineData(MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, "Allow LAN/Private Base URL", PluginSettingType.Boolean, "false")] + [InlineData(MusicBrainzSettingsKeys.CONTACT_EMAIL, "Contact Email", PluginSettingType.Text, null)] + [InlineData(MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, "Search Result Limit", PluginSettingType.Number, "10")] + [InlineData(MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, "Release Lookup Limit", PluginSettingType.Number, "25")] + [InlineData(MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, "Minimum Request Interval (seconds)", PluginSettingType.Number, "1.0")] + public void GetSettingsSchema_WhenCalled_ShouldDescribeEachSettingCorrectly(string key, string label, PluginSettingType type, string? defaultValue) + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + PluginSettingDescriptorDto descriptor = Assert.Single(result, candidate => candidate.Key == key); + Assert.Equal(label, descriptor.Label); + Assert.Equal(type, descriptor.Type); + Assert.Equal(defaultValue, descriptor.DefaultValue); + Assert.Null(descriptor.AllowedValues); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheThreeKeyedMetadataProviders() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Equal(3, serviceProvider.GetKeyedServices(MusicBrainzPlugin.s_pluginId).Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzTrackMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzTrackMetadataProviderTests.cs new file mode 100644 index 00000000..e3001edc --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzTrackMetadataProviderTests.cs @@ -0,0 +1,730 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzTrackMetadataProviderTests +{ + private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid s_recordingId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + private static readonly Guid s_secondRecordingId = Guid.Parse("33333333-3333-3333-3333-333333333333"); + private static readonly Guid s_workId = Guid.Parse("44444444-4444-4444-4444-444444444444"); + + private readonly TrackMetadataLookupDtoFixture _trackMetadataLookupDtoFixture = new(); + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("MusicBrainz", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnTrue() + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task GetSearchResultsAsync_WhenTheTitleIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? title) + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: title); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheSearchReturnsRecordings_ShouldMapEveryTitledOneAndSkipTheUntitledOnes() + { + // Arrange + const string SEARCH_JSON = """ + { + "count": 3, + "recordings": [ + { "id": "22222222-2222-2222-2222-222222222222", "title": "The Track" }, + { "id": "33333333-3333-3333-3333-333333333333", "title": "Other Track" }, + { "id": "44444444-4444-4444-4444-444444444444", "title": null } + ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: " The \"Track\" ", artistName: "The Artist", releaseName: "The Album"); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal("The Track", result[0].Title); + Assert.Equal("Other Track", result[1].Title); + Assert.Equal(1, handler.CallCount); + Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query); + string query = Uri.UnescapeDataString(handler.Requests[0].RequestUri!.Query); + Assert.Contains("recording:\"The Track\"", query); + Assert.Contains("artist:\"The Artist\"", query); + Assert.Contains("release:\"The Album\"", query); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTracklistMatchesTheRecordingIdentifier_ShouldResolveTheTrackFromTheRelease() + { + // Arrange + string releaseJson = TwoTrackReleaseJson(); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_secondRecordingId, trackNumber: 9, discNumber: 1); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTracklistDoesNotMatch_ShouldFallBackToTheRecordingIdentifier() + { + // Arrange + Guid fallbackRecordingId = Guid.NewGuid(); + string releaseJson = TwoTrackReleaseJson(); + string recordingJson = RecordingJson(fallbackRecordingId, "Searched Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json( + request.RequestUri!.AbsolutePath.Contains("/release/") ? releaseJson : recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: fallbackRecordingId, trackNumber: 99); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + // The release has no matching track, so it falls through to the recording lookup. + Assert.NotNull(result); + Assert.Equal(fallbackRecordingId, result.MusicBrainzRecordingId); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseIsNotFound_ShouldFallBackToTheRecordingIdentifier() + { + // Arrange + string recordingJson = RecordingJson(s_recordingId, "Searched Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.AbsolutePath.Contains("/release/") ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_recordingId, result.MusicBrainzRecordingId); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheMatchedTrackHasNoRecording_ShouldFallThroughToTheSearch() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "Track Without Recording" } ] } ] + } + """; + const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Searched Track"}]}"""; + string recordingJson = RecordingJson(s_recordingId, "Searched Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.Query.Contains("query=") + ? Json(SEARCH_JSON) + : request.RequestUri.AbsolutePath.Contains("/recording/") + ? Json(recordingJson) + : Json(RELEASE_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Searched Track", trackNumber: 1, discNumber: 1); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Searched Track", result.Title); + Assert.Equal(s_recordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTrackCarriesAnInlineWork_ShouldUseItWithoutAFurtherLookup() + { + // Arrange + string releaseJson = $$""" + { + "id": "{{s_releaseId:D}}", + "title": "The Release", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "Inline Work", "type": "Song" } } ] } } ] } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.Work); + Assert.Equal(s_workId, result.Work.MusicBrainzWorkId); + Assert.Equal("Inline Work", result.Work.Title); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheInlineWorkRelationHasNoWorkPayload_ShouldFallBackToTheWorkIdentifierOfTheTags() + { + // Arrange + string releaseJson = $$""" + { + "id": "{{s_releaseId:D}}", + "title": "The Release", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work" } ] } } ] } ] + } + """; + string workJson = $$"""{"id":"{{s_workId:D}}","title":"Tagged Work"}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json( + request.RequestUri!.AbsolutePath.Contains("/release/") ? releaseJson : workJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: s_workId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.Work); + Assert.Equal(s_workId, result.Work.MusicBrainzWorkId); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTrackCarriesAWorkWithoutAWorkTitleInTheTags_ShouldNotQueryTheWorkAgain() + { + // Arrange + string releaseJson = $$""" + { + "id": "{{s_releaseId:D}}", + "title": "The Release", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "Inline Work" } } ] } } ] } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: Guid.NewGuid()); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Inline Work", result.Work!.Title); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenOnlyTheRecordingIdentifierIsPresent_ShouldResolveTheRecordingItsWorkAndItsRelease() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "The Work" } } ], + "releases": [ { "id": "{{s_releaseId:D}}", "title": "The Release", "text-representation": { "language": "eng", "script": "Latn" } } ] + } + """; + string workJson = $$"""{"id":"{{s_workId:D}}","title":"The Work","type":"Song"}"""; + string releaseJson = $$"""{"id":"{{s_releaseId:D}}","title":"The Release","text-representation":{"language":"eng","script":"Latn"} }"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.AbsolutePath.Contains("/work/") ? Json(workJson) + : request.RequestUri.AbsolutePath.Contains("/release/") ? Json(releaseJson) + : Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_recordingId, result.MusicBrainzRecordingId); + Assert.Equal(s_workId, result.Work!.MusicBrainzWorkId); + Assert.Equal("The Work", result.Work.Title); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language.LanguageCode); + Assert.Equal(3, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheRecordingRelationsCarryAnUnparsableWorkIdentifier_ShouldUseTheEmbeddedWork() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "relations": [ { "target-type": "work", "work": { "id": "not-a-guid", "title": "Embedded Work" } } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Embedded Work", result.Work!.Title); + Assert.Null(result.Work.MusicBrainzWorkId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheRecordingHasNoWorkRelation_ShouldReturnATrackWithoutWork() + { + // Arrange + string recordingJson = RecordingJson(s_recordingId, "The Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Work); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheRecordingReferencesAnUnparsableRelease_ShouldReturnATrackWithoutRelease() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "releases": [ { "id": "not-a-guid", "title": "The Release" } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Language); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheRecordingHasNoReleases_ShouldReturnATrackWithoutRelease() + { + // Arrange + string recordingJson = RecordingJson(s_recordingId, "The Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Script); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheIsrcMatchesARecordingWithAParsableIdentifier_ShouldResolveItInFull() + { + // Arrange + const string ISRC_JSON = """{"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Isrc Track"}]}"""; + string recordingJson = RecordingJson(s_recordingId, "Resolved Isrc Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.AbsolutePath.Contains("/isrc/") ? Json(ISRC_JSON) : Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Resolved Isrc Track", result.Title); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheIsrcMatchesARecordingWithAnUnparsableIdentifier_ShouldReturnItAsIs() + { + // Arrange + const string ISRC_JSON = """{"recordings":[{"id":"not-a-guid","title":"Raw Isrc Track"}]}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(ISRC_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Raw Isrc Track", result.Title); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheIsrcMatchesNothing_ShouldReturnNullWithoutATitle() + { + // Arrange + const string ISRC_JSON = """{"recordings":[]}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(ISRC_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenOnlyTheTitleIsPresent_ShouldSearchAndResolveTheRecordingInFull() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Searched Track"}]}"""; + string recordingJson = RecordingJson(s_recordingId, "Resolved Searched Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.Query.Contains("query=") ? Json(SEARCH_JSON) : Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: "Searched Track"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Resolved Searched Track", result.Title); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchReturnsNothing_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":0,"recordings":[]}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: "Searched Track"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenNoLookupInformationIsPresent_ShouldReturnNullWithoutAnyRequest() + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheLocalDiscNumberDoesNotMatchAnyMedium_ShouldReturnNull() + { + // Arrange + string releaseJson = TwoTrackReleaseJson(); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, discNumber: 9); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenOnlyTheTrackNumberIsPresent_ShouldSelectTheTrackOnAnyDisc() + { + // Arrange + string releaseJson = TwoTrackReleaseJson(); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, trackNumber: 2); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTitleSinglesOutATrack_ShouldSelectIt() + { + // Arrange + string releaseJson = TwoTrackReleaseJson(); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Second Track"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenSeveralTracksShareTheTitle_ShouldUseTheDurationAsATieBreaker() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "media": [ { "position": 1, "track-count": 2, "tracks": [ + { "position": 1, "title": "Same Title", "length": 100000, "recording": { "id": "22222222-2222-2222-2222-222222222222", "title": "Same Title" } }, + { "position": 2, "title": "Same Title", "length": 200000, "recording": { "id": "33333333-3333-3333-3333-333333333333", "title": "Same Title" } } + ] } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Same Title", durationInSeconds: 190); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenSeveralTracksShareTheTitleAndNoDurationIsKnown_ShouldSelectTheFirstOne() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "media": [ { "position": 1, "track-count": 2, "tracks": [ + { "position": 1, "title": "Same Title", "length": 100000, "recording": { "id": "22222222-2222-2222-2222-222222222222", "title": "Same Title" } }, + { "position": 2, "title": "Same Title", "length": 200000, "recording": { "id": "33333333-3333-3333-3333-333333333333", "title": "Same Title" } } + ] } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Different Title"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_recordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryAWorkIdButMusicBrainzAlreadyLinkedAWork_ShouldResolveTheMusicBrainzWorkInFull() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "MusicBrainz Work" } } ] + } + """; + string workJson = $$"""{"id":"{{s_workId:D}}","title":"Tagged Work"}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json( + request.RequestUri!.AbsolutePath.Contains("/work/") ? workJson : recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: Guid.NewGuid()); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + // The work identifier linked by MusicBrainz is resolved in full, taking precedence over the work identifier of the tags. + Assert.Equal(s_workId, result.Work!.MusicBrainzWorkId); + Assert.Equal("Tagged Work", result.Work.Title); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTracksHaveMissingOrUnparsableRecordingIdentifiers_ShouldFallBackToTheRecordingLookup() + { + // Arrange + Guid fallbackRecordingId = Guid.NewGuid(); + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "media": [ { "position": 1, "track-count": 2, "tracks": [ + { "position": 1, "title": "Track Without Recording" }, + { "position": 2, "title": "Track With Bad Recording", "recording": { "id": "not-a-guid", "title": "Track With Bad Recording" } } + ] } ] + } + """; + string recordingJson = RecordingJson(fallbackRecordingId, "Fallback Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json( + request.RequestUri!.AbsolutePath.Contains("/release/") ? RELEASE_JSON : recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: fallbackRecordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(fallbackRecordingId, result.MusicBrainzRecordingId); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenAWorkRelationHasNoWork_ShouldReturnATrackWithoutWork() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "relations": [ { "target-type": "work" } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Work); + } + + /// + /// Creates a whose requests are answered by the provided stub handler. + /// + /// The factory that produces the response of a request. + /// The created provider and its stub handler. + private (MusicBrainzTrackMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func responseFactory) + { + StubHttpMessageHandler handler = new(responseFactory); + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: "http://localhost/", + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.Zero)); + MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + return (new MusicBrainzTrackMetadataProvider(httpClient, settingsProvider), handler); + } + + /// + /// Creates the JSON of a release with two tracks, each with its own recording. + /// + /// The JSON of the release. + private static string TwoTrackReleaseJson() + { + return $$""" + { + "id": "{{s_releaseId:D}}", + "title": "The Release", + "media": [ { "position": 1, "track-count": 2, "tracks": [ + { "position": 1, "title": "First Track", "recording": { "id": "{{s_recordingId:D}}", "title": "First Track" } }, + { "position": 2, "title": "Second Track", "recording": { "id": "{{s_secondRecordingId:D}}", "title": "Second Track" } } + ] } ] + } + """; + } + + /// + /// Creates the JSON of a recording response. + /// + /// The MusicBrainz identifier of the recording. + /// The title of the recording. + /// The JSON of the recording response. + private static string RecordingJson(Guid id, string title) + { + return $$"""{"id":"{{id:D}}","title":"{{title}}"}"""; + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs new file mode 100644 index 00000000..00c0643e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs @@ -0,0 +1,359 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Settings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzSettingsProviderTests +{ + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public async Task GetAsync_WhenNoStoreIsAvailable_ShouldReturnTheDefaults() + { + // Arrange + MusicBrainzSettingsDto defaults = CreateDefaults(); + MusicBrainzSettingsProvider sut = new(null, Guid.NewGuid(), defaults); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.NotSame(defaults, result); + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + Assert.False(result.DoesAllowPrivateBaseUrl); + Assert.Equal("Lumina-MusicBrainz/1.0", result.UserAgent); + Assert.Equal("default@example.com", result.ContactEmail); + Assert.Equal(10, result.SearchResultLimit); + Assert.Equal(25, result.ReleaseLookupLimit); + Assert.Equal(TimeSpan.FromSeconds(1), result.MinimumRequestInterval); + } + + [Fact] + public async Task GetAsync_WhenTheStoreReturnsNoSettings_ShouldReturnTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns((IReadOnlyDictionary?)null); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + Assert.Equal(10, result.SearchResultLimit); + } + + [Fact] + public async Task GetAsync_WhenEverySettingIsPersisted_ShouldOverlayThemOverTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary + { + [MusicBrainzSettingsKeys.BASE_URL] = "https://mirror.example/ws/2/", + [MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL] = "true", + [MusicBrainzSettingsKeys.CONTACT_EMAIL] = " contact@example.com ", + [MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT] = "42", + [MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT] = "30", + [MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "2.5" + }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://mirror.example/ws/2/", result.BaseUrl); + Assert.True(result.DoesAllowPrivateBaseUrl); + Assert.Equal("contact@example.com", result.ContactEmail); + Assert.Equal(42, result.SearchResultLimit); + Assert.Equal(30, result.ReleaseLookupLimit); + Assert.Equal(TimeSpan.FromSeconds(2.5), result.MinimumRequestInterval); + } + + [Theory] + [InlineData("not-a-url")] // a value that is not an URI at all + [InlineData("ftp://mirror.example/")] // an absolute URI with an unsupported scheme + [InlineData("relative/path")] // a relative URI + [InlineData(" ")] // only white space + public async Task GetAsync_WhenThePersistedBaseUrlIsInvalid_ShouldKeepTheDefaultBaseUrl(string baseUrl) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.BASE_URL] = baseUrl }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + } + + [Theory] + [InlineData("http://127.0.0.1/ws/2/")] // IPv4 loopback + [InlineData("http://localhost/ws/2/")] // loopback host name + [InlineData("http://[::1]/ws/2/")] // IPv6 loopback + [InlineData("http://169.254.169.254/latest/meta-data/")] // link local cloud metadata endpoint + [InlineData("http://10.0.0.5/ws/2/")] // private class A range + [InlineData("http://172.16.0.1/ws/2/")] // private class B range + [InlineData("http://192.168.1.10/ws/2/")] // private class C range + [InlineData("http://0.0.0.0/ws/2/")] // unspecified address + [InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range + public async Task GetAsync_WhenThePersistedBaseUrlPointsAtALocalOrPrivateHost_ShouldKeepTheDefaultBaseUrl(string baseUrl) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.BASE_URL] = baseUrl }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + } + + [Theory] + [InlineData("http://192.168.1.10/ws/2/")] // private class C range, a typical self hosted mirror + [InlineData("http://localhost/ws/2/")] // loopback host name + [InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range + public async Task GetAsync_WhenPrivateBaseUrlsAreExplicitlyAllowed_ShouldApplyThem(string baseUrl) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary + { + [MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL] = "true", + [MusicBrainzSettingsKeys.BASE_URL] = baseUrl + }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(baseUrl, result.BaseUrl); + } + + [Theory] + [InlineData("user\r\n@example.com")] // carriage return and line feed injection + [InlineData("user@example.com\r\nX-Injected: value")] // header injection attempt + [InlineData("user(comment)@example.com")] // parentheses break the user agent comment + [InlineData("user\"quoted\"@example.com")] // quotes break the header value + [InlineData("user example@example.com")] // an inner space is not a valid token character + public async Task GetAsync_WhenThePersistedContactEmailContainsUnsafeCharacters_ShouldDropIt(string storedEmail) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.CONTACT_EMAIL] = storedEmail }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Null(result.ContactEmail); + } + + [Fact] + public async Task GetAsync_WhenThePersistedBaseUrlIsAnAbsoluteHttpUrl_ShouldApplyIt() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.BASE_URL] = "http://mirror.example/ws/2/" }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("http://mirror.example/ws/2/", result.BaseUrl); + } + + [Fact] + public async Task GetAsync_WhenThePersistedBaseUrlIsNull_ShouldKeepTheDefaultBaseUrl() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.BASE_URL] = null! }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + } + + [Theory] + [InlineData("", null)] // an empty value clears the email + [InlineData(" ", null)] // a white space value clears the email + [InlineData(" user@example.com ", "user@example.com")] // a value with surrounding white space is trimmed + public async Task GetAsync_WhenThePersistedContactEmailIsPresent_ShouldSetOrClearIt(string storedEmail, string? expectedEmail) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.CONTACT_EMAIL] = storedEmail }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedEmail, result.ContactEmail); + } + + [Theory] + [InlineData("42", 42)] + [InlineData("0", 1)] // a limit of zero is clamped to one + [InlineData("-5", 1)] // a negative limit is clamped to one + [InlineData("not-a-number", 10)] // an unparsable value keeps the default + public async Task GetAsync_WhenThePersistedSearchResultLimitIsPresent_ShouldParseAndClampIt(string storedLimit, int expectedLimit) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT] = storedLimit }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedLimit, result.SearchResultLimit); + } + + [Theory] + [InlineData("30", 30)] + [InlineData("0", 1)] // a limit of zero is clamped to one + [InlineData("-5", 1)] // a negative limit is clamped to one + [InlineData("not-a-number", 25)] // an unparsable value keeps the default + public async Task GetAsync_WhenThePersistedReleaseLookupLimitIsPresent_ShouldParseAndClampIt(string storedLimit, int expectedLimit) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT] = storedLimit }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedLimit, result.ReleaseLookupLimit); + } + + [Theory] + [InlineData("2.5", 2.5)] + [InlineData("0", 0)] // an interval of zero is allowed + [InlineData("-3", 0)] // a negative interval is clamped to zero + [InlineData("not-a-number", 1)] // an unparsable value keeps the default + public async Task GetAsync_WhenThePersistedMinimumRequestIntervalIsPresent_ShouldParseAndClampIt(string storedInterval, double expectedSeconds) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = storedInterval }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(TimeSpan.FromSeconds(expectedSeconds), result.MinimumRequestInterval); + } + + [Fact] + public async Task GetAsync_WhenCalledTwice_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto first = await sut.GetAsync(CancellationToken.None); + MusicBrainzSettingsDto second = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Same(first, second); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto[] results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => sut.GetAsync(CancellationToken.None))); + + // Assert + Assert.All(results, result => Assert.Same(results[0], result)); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + MusicBrainzSettingsProvider sut = new(null, Guid.NewGuid(), CreateDefaults()); + + // Act + Task Act() + { + return sut.GetAsync(cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + /// + /// Creates the default settings used by the tests of the provider. + /// + /// The default settings. + private MusicBrainzSettingsDto CreateDefaults() + { + return _musicBrainzSettingsDtoFixture.Create( + baseUrl: "https://musicbrainz.org/ws/2/", + doesAllowPrivateBaseUrl: false, + userAgent: "Lumina-MusicBrainz/1.0", + contactEmail: "default@example.com", + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.FromSeconds(1)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Lumina.Plugins.MusicBrainz.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Lumina.Plugins.MusicBrainz.UnitTests.csproj new file mode 100644 index 00000000..68c1fef9 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Lumina.Plugins.MusicBrainz.UnitTests.csproj @@ -0,0 +1,47 @@ + + + + net10.0 + disable + enable + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/Models/DTO/Settings/OpenLibrarySettingsDtoTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/Models/DTO/Settings/OpenLibrarySettingsDtoTests.cs index ef81ed0e..520e9673 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/Models/DTO/Settings/OpenLibrarySettingsDtoTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/Models/DTO/Settings/OpenLibrarySettingsDtoTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; +using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -12,11 +13,13 @@ namespace Lumina.Plugins.OpenLibrary.UnitTests.Common.Models.DTO.Settings; [ExcludeFromCodeCoverage] public class OpenLibrarySettingsDtoTests { + private readonly OpenLibrarySettingsDtoFixture _openLibrarySettingsDtoFixture = new(); + [Fact] public void Defaults_WhenCreated_ShouldUseTheDocumentedDefaultValues() { // Arrange - OpenLibrarySettingsDto sut = new(); + OpenLibrarySettingsDto sut = _openLibrarySettingsDtoFixture.Create(includeUserAgent: false, includeSearchResultLimit: false, includeWorkEditionLimit: false, includeMinimumRequestInterval: false); // Act @@ -32,7 +35,7 @@ public class OpenLibrarySettingsDtoTests public void Setters_WhenAssigned_ShouldExposeTheAssignedValues() { // Arrange - OpenLibrarySettingsDto sut = new(); + OpenLibrarySettingsDto sut = _openLibrarySettingsDtoFixture.Create(); TimeSpan expectedInterval = TimeSpan.FromSeconds(3); // Act diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs index c0e6f138..766b53e0 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs @@ -26,7 +26,7 @@ namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Api; [ExcludeFromCodeCoverage] public class OpenLibraryHttpClientTests { - private readonly OpenLibrarySettingsDtoFixture _settingsFixture = new(); + private readonly OpenLibrarySettingsDtoFixture _openLibrarySettingsDtoFixture = new(); private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); [Fact] @@ -36,7 +36,7 @@ public class OpenLibraryHttpClientTests HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); // Act - _ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create())); + _ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create())); // Assert Assert.Equal(new Uri("https://openlibrary.org/"), httpClient.BaseAddress); @@ -53,7 +53,7 @@ public class OpenLibraryHttpClientTests }; // Act - _ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create())); + _ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create())); // Assert Assert.Equal(existingBaseAddress, httpClient.BaseAddress); @@ -66,7 +66,7 @@ public class OpenLibraryHttpClientTests StubOpenLibraryHttpMessageHandler handler = new(); handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); HttpClient httpClient = new(handler); - OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(userAgent: "CustomAgent/2.0"))); + OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create(userAgent: "CustomAgent/2.0"))); // Act await sut.GetEditionAsync("OL1M", CancellationToken.None); @@ -83,7 +83,7 @@ public class OpenLibraryHttpClientTests handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); HttpClient httpClient = new(handler); httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("ExistingAgent/1.0"); - OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(userAgent: "ConfiguredAgent/2.0"))); + OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create(userAgent: "ConfiguredAgent/2.0"))); // Act await sut.GetEditionAsync("OL1M", CancellationToken.None); @@ -99,7 +99,7 @@ public class OpenLibraryHttpClientTests StubOpenLibraryHttpMessageHandler handler = new(); handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); HttpClient httpClient = new(handler); - OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(contactEmail: "contact@example.com"))); + OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create(contactEmail: "contact@example.com"))); // Act await sut.GetEditionAsync("OL1M", CancellationToken.None); @@ -115,7 +115,7 @@ public class OpenLibraryHttpClientTests StubOpenLibraryHttpMessageHandler handler = new(); handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); HttpClient httpClient = new(handler); - OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(contactEmail: null))); + OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create(contactEmail: null))); // Act await sut.GetEditionAsync("OL1M", CancellationToken.None); @@ -434,7 +434,7 @@ public class OpenLibraryHttpClientTests _ => attempts++ == 0 ? new HttpResponseMessage(HttpStatusCode.InternalServerError) : StubOpenLibraryHttpMessageHandler.CreateJsonResponse(HttpStatusCode.OK, """{"key":"/works/OL123W","title":"Work"}""")); - OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero)); // Act OpenLibraryWorkResponse? result = await sut.GetWorkAsync("OL123W", CancellationToken.None); @@ -464,7 +464,7 @@ public class OpenLibraryHttpClientTests return StubOpenLibraryHttpMessageHandler.CreateJsonResponse(HttpStatusCode.OK, """{"key":"/works/OL123W","title":"Work"}"""); }); - OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero)); // Act OpenLibraryWorkResponse? result = await sut.GetWorkAsync("OL123W", CancellationToken.None); @@ -483,7 +483,7 @@ public class OpenLibraryHttpClientTests handler.AddRoute( request => request.RequestUri!.AbsolutePath == "/works/OL123W.json", _ => new HttpResponseMessage(HttpStatusCode.InternalServerError)); - OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero)); // Act async Task Act() @@ -504,7 +504,7 @@ public class OpenLibraryHttpClientTests handler.AddRoute( request => request.RequestUri!.AbsolutePath == "/works/OL123W.json", _ => new HttpResponseMessage(HttpStatusCode.BadRequest)); - OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero)); // Act async Task Act() @@ -523,7 +523,7 @@ public class OpenLibraryHttpClientTests // Arrange StubOpenLibraryHttpMessageHandler handler = new(); handler.MapPath("/works/OL1W.json", """{"key":"/works/OL1W","title":"Work"}"""); - OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.FromMilliseconds(300))); + OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.FromMilliseconds(300))); // Act Stopwatch stopwatch = Stopwatch.StartNew(); @@ -562,7 +562,7 @@ public class OpenLibraryHttpClientTests private OpenLibraryHttpClient CreateSut(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null) { HttpClient httpClient = new(handler); - OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), settings ?? _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero)); return new OpenLibraryHttpClient(httpClient, settingsProvider); } } diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs index 5218aefa..978e5950 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs @@ -27,14 +27,14 @@ namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Mapping; public class OpenLibraryMapperTests { private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); - private readonly OpenLibraryEditionResponseFixture _editionResponseFixture = new(); - private readonly OpenLibraryWorkResponseFixture _workResponseFixture = new(); - private readonly OpenLibrarySearchDocumentResponseFixture _searchDocumentResponseFixture = new(); - private readonly OpenLibraryAuthorResponseFixture _authorResponseFixture = new(); - private readonly OpenLibraryRatingsResponseFixture _ratingsResponseFixture = new(); - private readonly OpenLibraryRatingSummaryResponseFixture _ratingSummaryResponseFixture = new(); - private readonly OpenLibraryKeyReferenceResponseFixture _keyReferenceResponseFixture = new(); - private readonly OpenLibraryWorkAuthorResponseFixture _workAuthorResponseFixture = new(); + private readonly OpenLibraryEditionResponseFixture _openLibraryEditionResponseFixture = new(); + private readonly OpenLibraryWorkResponseFixture _openLibraryWorkResponseFixture = new(); + private readonly OpenLibrarySearchDocumentResponseFixture _openLibrarySearchDocumentResponseFixture = new(); + private readonly OpenLibraryAuthorResponseFixture _openLibraryAuthorResponseFixture = new(); + private readonly OpenLibraryRatingsResponseFixture _openLibraryRatingsResponseFixture = new(); + private readonly OpenLibraryRatingSummaryResponseFixture _openLibraryRatingSummaryResponseFixture = new(); + private readonly OpenLibraryKeyReferenceResponseFixture _openLibraryKeyReferenceResponseFixture = new(); + private readonly OpenLibraryWorkAuthorResponseFixture _openLibraryWorkAuthorResponseFixture = new(); [Theory] [InlineData("978-0-306-40615-7", "9780306406157")] @@ -154,7 +154,7 @@ public class OpenLibraryMapperTests { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); - OpenLibrarySearchDocumentResponse document = _searchDocumentResponseFixture.Create( + OpenLibrarySearchDocumentResponse document = _openLibrarySearchDocumentResponseFixture.Create( key: "/works/OL12345W", title: "Search Title", authorNames: ["Search Author"], @@ -200,7 +200,7 @@ public class OpenLibraryMapperTests // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(isbn: "978-0-306-40615-7"); JsonElement identifiers = JsonDocument.Parse("""{"amazon":["B000001"],"goodreads":["12345"],"google":["gid"],"librarything":["ltid"],"barnesandnoble":["bnid"],"apple":["apid"]}""").RootElement; - OpenLibraryEditionResponse edition = _editionResponseFixture.Create( + OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create( key: "/books/OL100M", title: "Edition Title", publishDate: "2010-05-01", @@ -216,10 +216,10 @@ public class OpenLibraryMapperTests lccn: ["79042755"], oclcNumbers: ["1234567"], identifiers: identifiers, - languages: [_keyReferenceResponseFixture.Create(key: "/languages/eng")], - works: [_keyReferenceResponseFixture.Create(key: "/works/OL200W")], + languages: [_openLibraryKeyReferenceResponseFixture.Create(key: "/languages/eng")], + works: [_openLibraryKeyReferenceResponseFixture.Create(key: "/works/OL200W")], contributions: ["John Smith (Illustrator)"]); - OpenLibraryWorkResponse work = _workResponseFixture.Create( + OpenLibraryWorkResponse work = _openLibraryWorkResponseFixture.Create( key: "/works/OL200W", title: "Work Title", originalTitle: "Original Title", @@ -227,10 +227,10 @@ public class OpenLibraryMapperTests firstPublishDate: "1987-06-01", subjects: ["Science fiction", "History", "Space"], genres: ["Fantasy"], - authors: [_workAuthorResponseFixture.Create(author: _keyReferenceResponseFixture.Create(key: "/authors/OL1A"))], - originalLanguages: [_keyReferenceResponseFixture.Create(key: "/languages/fre")]); - OpenLibraryAuthorResponse author = _authorResponseFixture.Create(key: "/authors/OL1A", name: "Test Author", personalName: "Test Personal Name"); - OpenLibraryRatingsResponse ratings = _ratingsResponseFixture.Create(_ratingSummaryResponseFixture.Create(average: 4.2m, count: 100)); + authors: [_openLibraryWorkAuthorResponseFixture.Create(author: _openLibraryKeyReferenceResponseFixture.Create(key: "/authors/OL1A"))], + originalLanguages: [_openLibraryKeyReferenceResponseFixture.Create(key: "/languages/fre")]); + OpenLibraryAuthorResponse author = _openLibraryAuthorResponseFixture.Create(key: "/authors/OL1A", name: "Test Author", personalName: "Test Personal Name"); + OpenLibraryRatingsResponse ratings = _openLibraryRatingsResponseFixture.Create(_openLibraryRatingSummaryResponseFixture.Create(average: 4.2m, count: 100)); // Act BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings); @@ -287,7 +287,7 @@ public class OpenLibraryMapperTests { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); - OpenLibraryWorkResponse work = _workResponseFixture.Create(subjects: ["Science fiction", "History", "Space"]); + OpenLibraryWorkResponse work = _openLibraryWorkResponseFixture.Create(subjects: ["Science fiction", "History", "Space"]); // Act BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null); @@ -304,7 +304,7 @@ public class OpenLibraryMapperTests { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); - OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(firstPublishYear: 2001); + OpenLibrarySearchDocumentResponse fallback = _openLibrarySearchDocumentResponseFixture.Create(firstPublishYear: 2001); // Act BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback); @@ -319,7 +319,7 @@ public class OpenLibraryMapperTests { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); - OpenLibraryEditionResponse edition = _editionResponseFixture.Create(languages: [_keyReferenceResponseFixture.Create(key: "/languages/xxq")]); + OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create(languages: [_openLibraryKeyReferenceResponseFixture.Create(key: "/languages/xxq")]); // Act BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null); @@ -336,7 +336,7 @@ public class OpenLibraryMapperTests { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); - OpenLibraryWorkResponse work = _workResponseFixture.Create(description: JsonDocument.Parse("\"A plain description\"").RootElement); + OpenLibraryWorkResponse work = _openLibraryWorkResponseFixture.Create(description: JsonDocument.Parse("\"A plain description\"").RootElement); // Act BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null); @@ -370,7 +370,7 @@ public class OpenLibraryMapperTests { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); - OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(ratingsAverage: 3.5m, ratingsCount: 10); + OpenLibrarySearchDocumentResponse fallback = _openLibrarySearchDocumentResponseFixture.Create(ratingsAverage: 3.5m, ratingsCount: 10); // Act BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback); @@ -386,7 +386,7 @@ public class OpenLibraryMapperTests { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); - OpenLibraryEditionResponse edition = _editionResponseFixture.Create(series: ["Book 2 of the trilogy"]); + OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create(series: ["Book 2 of the trilogy"]); // Act BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null); @@ -401,11 +401,11 @@ public class OpenLibraryMapperTests { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); - OpenLibraryEditionResponse edition = _editionResponseFixture.Create( + OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create( sourceRecords: ["amazon:B000002", "google:gid2"], oclcNumbers: ["999999"], isbn13: ["9780306406157"]); - OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create( + OpenLibrarySearchDocumentResponse fallback = _openLibrarySearchDocumentResponseFixture.Create( amazonIds: ["B000003"], goodreadsIds: ["777"], googleIds: ["gid3"], diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs index 1c4994f0..915d96f7 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs @@ -26,7 +26,7 @@ namespace Lumina.Plugins.OpenLibrary.UnitTests.Core; [ExcludeFromCodeCoverage] public class OpenLibraryBookMetadataProviderTests { - private readonly OpenLibrarySettingsDtoFixture _settingsFixture = new(); + private readonly OpenLibrarySettingsDtoFixture _openLibrarySettingsDtoFixture = new(); private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); private const string EDITION_JSON = """{"key":"/books/OL100M","title":"Edition Title","publish_date":"2010-05-01","number_of_pages":320,"physical_format":"Hardcover","edition_name":"First Edition","series":["The Series"],"volume":"Vol. 3","publishers":["Publisher Co"],"isbn_13":["9780306406157"],"languages":[{"key":"/languages/eng"}],"works":[{"key":"/works/OL200W"}]}"""; @@ -230,7 +230,7 @@ public class OpenLibraryBookMetadataProviderTests public async Task GetSearchResultsAsync_WhenLookupHasNoPath_ShouldThrowArgumentNullException() { // Arrange - BookMetadataLookupDto lookup = new(Guid.NewGuid(), null!, Isbn: "978-0-306-40615-7"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(includePath: false, isbn: "978-0-306-40615-7"); OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); // Act @@ -438,7 +438,7 @@ public class OpenLibraryBookMetadataProviderTests private OpenLibraryBookMetadataProvider CreateProvider(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null) { - OpenLibrarySettingsDto runtimeSettings = settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero); + OpenLibrarySettingsDto runtimeSettings = settings ?? _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero); OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), runtimeSettings); OpenLibraryHttpClient openLibraryHttpClient = new(new HttpClient(handler), settingsProvider); return new OpenLibraryBookMetadataProvider(openLibraryHttpClient, settingsProvider); diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Settings/OpenLibrarySettingsLoaderTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Settings/OpenLibrarySettingsLoaderTests.cs index b572683e..515d4e15 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Settings/OpenLibrarySettingsLoaderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Settings/OpenLibrarySettingsLoaderTests.cs @@ -15,13 +15,13 @@ namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Settings; [ExcludeFromCodeCoverage] public class OpenLibrarySettingsLoaderTests { - private readonly OpenLibrarySettingsDtoFixture _settingsFixture = new(); + private readonly OpenLibrarySettingsDtoFixture _openLibrarySettingsDtoFixture = new(); [Fact] public void Apply_WhenStoredSettingsContainValidValues_ShouldOverlayThemOntoTheRuntimeSettings() { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.CONTACT_EMAIL] = " contact@example.com ", @@ -44,7 +44,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenStoredSettingsAreEmpty_ShouldKeepTheRuntimeSettingsDefaults() { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create( + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create( userAgent: "Lumina-OpenLibrary/1.0", searchResultLimit: 10, workEditionLimit: 50, @@ -66,7 +66,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenStoredSettingsContainUnknownKeys_ShouldIgnoreThem() { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(searchResultLimit: 10, workEditionLimit: 50); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(searchResultLimit: 10, workEditionLimit: 50); Dictionary storedSettings = new() { ["UnknownSetting"] = "value" @@ -84,7 +84,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenContactEmailIsWhiteSpace_ShouldSetItToNull() { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.CONTACT_EMAIL] = " " @@ -97,11 +97,33 @@ public class OpenLibrarySettingsLoaderTests Assert.Null(settings.ContactEmail); } + [Theory] + [InlineData("user\r\n@example.com")] // carriage return and line feed injection + [InlineData("user@example.com\r\nX-Injected: value")] // header injection attempt + [InlineData("user(comment)@example.com")] // parentheses break the from header + [InlineData("user\"quoted\"@example.com")] // quotes break the header value + [InlineData("user example@example.com")] // an inner space is not a valid token character + public void Apply_WhenContactEmailContainsUnsafeCharacters_ShouldSetItToNull(string storedEmail) + { + // Arrange + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.CONTACT_EMAIL] = storedEmail + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Null(settings.ContactEmail); + } + [Fact] public void Apply_WhenSearchResultLimitIsNotParsable_ShouldKeepTheCurrentValue() { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(searchResultLimit: 10); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(searchResultLimit: 10); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "not-a-number" @@ -118,7 +140,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenSearchResultLimitIsNotParsableAndCurrentValueWasChanged_ShouldKeepTheChangedValue() { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(searchResultLimit: 7); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(searchResultLimit: 7); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "not-a-number" @@ -140,7 +162,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenSearchResultLimitIsParsable_ShouldClampItToAtLeastOne(string storedValue, int expected) { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = storedValue @@ -160,7 +182,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenWorkEditionLimitIsParsable_ShouldClampItToAtLeastOne(string storedValue, int expected) { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.WORK_EDITION_LIMIT] = storedValue @@ -177,7 +199,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenMinimumRequestIntervalIsNegative_ShouldClampItToZero() { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "-3" @@ -197,7 +219,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenMinimumRequestIntervalUsesInvariantCultureDecimalSeparator_ShouldParseIt(string storedValue, int expectedMilliseconds) { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = storedValue @@ -214,7 +236,7 @@ public class OpenLibrarySettingsLoaderTests public void Apply_WhenMinimumRequestIntervalIsNotParsable_ShouldKeepTheCurrentValue() { // Arrange - OpenLibrarySettingsDto settings = _settingsFixture.Create(minimumRequestInterval: TimeSpan.FromSeconds(1.1)); + OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.FromSeconds(1.1)); Dictionary storedSettings = new() { [OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "fast" diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Lumina.Plugins.OpenLibrary.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Lumina.Plugins.OpenLibrary.UnitTests.csproj index f13a09c3..c04c5986 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Lumina.Plugins.OpenLibrary.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Lumina.Plugins.OpenLibrary.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Lumina.Plugins.Pdf.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Lumina.Plugins.Pdf.UnitTests.csproj index e5717587..75e6ce76 100644 --- a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Lumina.Plugins.Pdf.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Lumina.Plugins.Pdf.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs index e80810c0..1f9e977f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointTests.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -27,6 +28,7 @@ public class GetPermissionsEndpointTests { private readonly IQueryHandler>> _mockHandler; private readonly GetPermissionsEndpoint _sut; + private readonly PermissionResponseFixture _permissionResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -44,9 +46,9 @@ public class GetPermissionsEndpointTests CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponse = [ - new(Guid.NewGuid(), AuthorizationPermission.CanViewUsers), - new(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers), - new(Guid.NewGuid(), AuthorizationPermission.CanRegisterUsers) + _permissionResponseFixture.Create(id: Guid.NewGuid(), permissionName: AuthorizationPermission.CanViewUsers), + _permissionResponseFixture.Create(id: Guid.NewGuid(), permissionName: AuthorizationPermission.CanDeleteUsers), + _permissionResponseFixture.Create(id: Guid.NewGuid(), permissionName: AuthorizationPermission.CanRegisterUsers) ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs index 1d63089b..0a42781d 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs @@ -177,7 +177,7 @@ public class AddAlbumEndpointTests command.Metadata == request.Metadata && command.MediaFormat == request.MediaFormat && command.Barcode == request.Barcode && - command.CatalogNumber == request.CatalogNumber && + command.CatalogNumbers == request.CatalogNumbers && command.MusicBrainzReleaseId == request.MusicBrainzReleaseId && command.MusicBrainzReleaseGroupId == request.MusicBrainzReleaseGroupId && command.MusicBrainzReleaseArtistId == request.MusicBrainzReleaseArtistId && diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs index a065ac95..36c8961f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs @@ -186,7 +186,7 @@ public class UpdateAlbumEndpointTests command.Metadata == request.Metadata && command.MediaFormat == request.MediaFormat && command.Barcode == request.Barcode && - command.CatalogNumber == request.CatalogNumber && + command.CatalogNumbers == request.CatalogNumbers && command.MusicBrainzReleaseId == request.MusicBrainzReleaseId && command.MusicBrainzReleaseGroupId == request.MusicBrainzReleaseGroupId && command.MusicBrainzReleaseArtistId == request.MusicBrainzReleaseArtistId && diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs index c907b11c..fee92864 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs @@ -159,7 +159,7 @@ public class AddArtistEndpointTests await _mockHandler.Received(1).HandleAsync( Arg.Is(command => command.LibraryId == libraryId.ToString() && - command.Name == request.Name && + command.Metadata == request.Metadata && command.Website == request.Website && command.MusicBrainzArtistId == request.MusicBrainzArtistId && command.Contributors == request.Contributors && diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs index dd3599f1..b78bc67e 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs @@ -172,7 +172,7 @@ public class UpdateArtistEndpointTests Arg.Is(command => command.LibraryId == libraryId.ToString() && command.ArtistId == artistId.ToString() && - command.Name == request.Name && + command.Metadata == request.Metadata && command.Website == request.Website && command.MusicBrainzArtistId == request.MusicBrainzArtistId && command.Contributors == request.Contributors && diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs index b94aff9c..43029748 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs @@ -151,7 +151,6 @@ public class AddTrackEndpointTests command.Work == request.Work && command.MusicBrainzRecordingId == request.MusicBrainzRecordingId && command.MusicBrainzTrackId == request.MusicBrainzTrackId && - command.MusicBrainzWorkId == request.MusicBrainzWorkId && command.Moods == request.Moods && command.Isrcs == request.Isrcs && command.Contributors == request.Contributors && diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs index f4c557f8..31623a6d 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs @@ -168,7 +168,6 @@ public class UpdateTrackEndpointTests command.Work == request.Work && command.MusicBrainzRecordingId == request.MusicBrainzRecordingId && command.MusicBrainzTrackId == request.MusicBrainzTrackId && - command.MusicBrainzWorkId == request.MusicBrainzWorkId && command.Moods == request.Moods && command.Isrcs == request.Isrcs && command.Contributors == request.Contributors && diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs new file mode 100644 index 00000000..47739d93 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetLibraryPathTemplatePartsEndpoint _sut; + private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new(); + private readonly LibraryPathTemplateCatalogResponseFixture _libraryPathTemplateCatalogResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryPathTemplatePartsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryPathTemplateCatalogResponse() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + LibraryPathTemplateCatalogResponse expectedResponse = _libraryPathTemplateCatalogResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "NotARealLibraryType"); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Library.UnknownLibraryType", "UnknownLibraryType"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.NotNull(validationProblemDetails.Instance); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "UnknownLibraryType" }, validationProblemDetails.Errors["Library.UnknownLibraryType"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryPathTemplatePartsQueryToSender() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "Music"); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryPathTemplateCatalogResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryType == request.LibraryType), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_libraryPathTemplateCatalogResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index 8afcb909..997f9de9 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -133,7 +133,7 @@ public class GetReadingResourceEndpointTests Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - ReadingResourceDataDto response = new(Guid.NewGuid().ToByteArray(), mimeType); + ReadingResourceDataDto response = _readingResourceDataDtoFixture.Create(data: Guid.NewGuid().ToByteArray(), mimeType: mimeType); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(response)); _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj index c8f4f2f9..bc6531f0 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs index cd7baeb9..4efbcf10 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -256,11 +256,7 @@ public class ExceptionHandlingMiddlewareTests { // Arrange DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true); - ProblemDetailsDto problemDetails = new() - { - Title = "General.Failure", - Status = 400 - }; + ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Failure", status: 400, includeType: false, includeDetail: false); _nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.BadRequest); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs index 466a7c72..82cf4c11 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Validation; +using Lumina.Presentation.Web.Fixtures.Common.Validation; using Microsoft.Extensions.Options; using NSubstitute; using System; @@ -17,15 +18,17 @@ namespace Lumina.Presentation.Web.UnitTests.Common.Validation; [ExcludeFromCodeCoverage] public class ValidationOptionsTests { + private readonly ValidationOptionsFixture _validationOptionsFixture = new(); + [Fact] public void Validate_WhenMatchingName_ShouldValidateOptions() { // Arrange string optionsName = "OptionsName"; - TestOptions options = new(); - IValidator validator = Substitute.For>(); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); + IValidator validator = Substitute.For>(); validator.Validate(options).Returns([]); - ValidationOptions sut = new(optionsName, validator); + ValidationOptions sut = new(optionsName, validator); // Act ValidateOptionsResult result = sut.Validate(optionsName, options); @@ -42,9 +45,9 @@ public class ValidationOptionsTests // Arrange string optionsName = "OptionsName"; string differentOptionsName = "DifferentOptionsName"; - TestOptions options = new(); - IValidator validator = Substitute.For>(); - ValidationOptions sut = new(optionsName, validator); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); + IValidator validator = Substitute.For>(); + ValidationOptions sut = new(optionsName, validator); // Act ValidateOptionsResult result = sut.Validate(differentOptionsName, options); @@ -58,10 +61,10 @@ public class ValidationOptionsTests public void Validate_WhenNullName_ShouldValidateOptions() { // Arrange - TestOptions options = new(); - IValidator validator = Substitute.For>(); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); + IValidator validator = Substitute.For>(); validator.Validate(options).Returns([]); - ValidationOptions sut = new(null, validator); + ValidationOptions sut = new(null, validator); // Act ValidateOptionsResult result = sut.Validate("AnyOptionsName", options); @@ -77,15 +80,15 @@ public class ValidationOptionsTests { // Arrange string optionsName = "OptionsName"; - IValidator validator = Substitute.For>(); - ValidationOptions sut = new(optionsName, validator); + IValidator validator = Substitute.For>(); + ValidationOptions sut = new(optionsName, validator); // Act Action act = () => sut.Validate(optionsName, null!); // Assert Assert.Throws(act); - validator.DidNotReceive().Validate(Arg.Any()); + validator.DidNotReceive().Validate(Arg.Any()); } [Fact] @@ -93,14 +96,14 @@ public class ValidationOptionsTests { // Arrange string optionsName = "OptionsName"; - TestOptions options = new(); - IValidator validator = Substitute.For>(); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); + IValidator validator = Substitute.For>(); List validationFailures = [ Error.Validation("PropertyName", "Error Message") ]; validator.Validate(options).Returns(validationFailures); - ValidationOptions sut = new(optionsName, validator); + ValidationOptions sut = new(optionsName, validator); // Act ValidateOptionsResult result = sut.Validate(optionsName, options); @@ -117,15 +120,15 @@ public class ValidationOptionsTests { // Arrange string optionsName = "OptionsName"; - TestOptions options = new(); - IValidator validator = Substitute.For>(); + ValidationOptionsFixture options = _validationOptionsFixture.Create(); + IValidator validator = Substitute.For>(); List validationFailures = [ Error.Validation("PropertyOne", "First Error Message"), Error.Validation("PropertyTwo", "Second Error Message") ]; validator.Validate(options).Returns(validationFailures); - ValidationOptions sut = new(optionsName, validator); + ValidationOptions sut = new(optionsName, validator); // Act ValidateOptionsResult result = sut.Validate(optionsName, options); @@ -137,12 +140,4 @@ public class ValidationOptionsTests Assert.Contains("Options validation failed for 'PropertyOne' with error: 'First Error Message'", result.Failures); Assert.Contains("Options validation failed for 'PropertyTwo' with error: 'Second Error Message'", result.Failures); } - - /// - /// Placeholder options type used to exercise the generic class. - /// - [ExcludeFromCodeCoverage] - public sealed class TestOptions - { - } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs index 9339fe4d..f35a6333 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs @@ -27,7 +27,7 @@ public class GetBookReadersEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly GetBookReadersEndpoint _sut; - private readonly GetBookReadersRequestFixture _requestFixture = new(); + private readonly GetBookReadersRequestFixture _getBookReadersRequestFixture = new(); private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new(); /// @@ -43,7 +43,7 @@ public class GetBookReadersEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithBookReaders() { // Arrange - GetBookReadersRequest request = _requestFixture.Create(); + GetBookReadersRequest request = _getBookReadersRequestFixture.Create(); LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)]; _mockApiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), Arg.Any()) .Returns(readers); @@ -62,7 +62,7 @@ public class GetBookReadersEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldRequestBookReadersFromApi() { // Arrange - GetBookReadersRequest request = _requestFixture.Create(); + GetBookReadersRequest request = _getBookReadersRequestFixture.Create(); LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)]; _mockApiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), Arg.Any()) .Returns(readers); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs new file mode 100644 index 00000000..0b5d8c43 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryPathTemplatePartsEndpoint _sut; + private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new(); + private readonly LibraryPathTemplateCatalogDtoFixture _libraryPathTemplateCatalogDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryPathTemplatePartsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithCatalog() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(); + LibraryPathTemplateCatalogDto catalog = _libraryPathTemplateCatalogDtoFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(catalog); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + JsonElement parts = data.GetProperty("parts"); + JsonElement defaultTemplateParts = data.GetProperty("defaultTemplateParts"); + Assert.Equal(catalog.Parts.Count, parts.GetArrayLength()); + Assert.Equal(catalog.DefaultTemplateParts.Count, defaultTemplateParts.GetArrayLength()); + + JsonElement firstPart = parts[0]; + Assert.Equal(catalog.Parts[0].Kind, firstPart.GetProperty("kind").GetString()); + Assert.Equal(catalog.Parts[0].ValueType, firstPart.GetProperty("valueType").GetString()); + Assert.Equal(catalog.Parts[0].DefaultRepresentation, firstPart.GetProperty("defaultRepresentation").GetString()); + Assert.Equal(catalog.Parts[0].IsOptionalByDefault, firstPart.GetProperty("isOptionalByDefault").GetBoolean()); + + JsonElement firstDefaultTemplatePart = defaultTemplateParts[0]; + Assert.Equal(catalog.DefaultTemplateParts[0].Kind, firstDefaultTemplatePart.GetProperty("kind").GetString()); + Assert.Equal(catalog.DefaultTemplateParts[0].Representation, firstDefaultTemplatePart.GetProperty("representation").GetString()); + Assert.Equal(catalog.DefaultTemplateParts[0].IsOptional, firstDefaultTemplatePart.GetProperty("isOptional").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestCatalogFromApiWithSubstitutedLibraryType() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "Music"); + LibraryPathTemplateCatalogDto catalog = _libraryPathTemplateCatalogDtoFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(catalog); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_PATH_TEMPLATE_PARTS.Replace("{libraryType}", "Music")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(); + LibraryPathTemplateCatalogDto catalog = _libraryPathTemplateCatalogDtoFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(catalog); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs index 82e2b72d..879cee64 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs @@ -26,7 +26,7 @@ public class SetBookReaderEnabledEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly SetBookReaderEnabledEndpoint _sut; - private readonly SetBookReaderEnabledRequestFixture _requestFixture = new(); + private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -41,7 +41,7 @@ public class SetBookReaderEnabledEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJson() { // Arrange - SetBookReaderEnabledRequest request = _requestFixture.Create(); + SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new EmptyRequest()); @@ -58,7 +58,7 @@ public class SetBookReaderEnabledEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendBookReaderEnabledChangeToApi() { // Arrange - SetBookReaderEnabledRequest request = _requestFixture.Create(); + SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new EmptyRequest()); string expectedEndpoint = ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index 6e2a9122..e07c1a51 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -28,7 +28,7 @@ public class GetReadingAvailabilityEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly GetReadingAvailabilityEndpoint _sut; private readonly ReadingAvailabilityDtoFixture _readingAvailabilityDtoFixture = new(); - private readonly GetBookReadingAvailabilityRequestFixture _requestFixture = new(); + private readonly GetBookReadingAvailabilityRequestFixture _getBookReadingAvailabilityRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +43,7 @@ public class GetReadingAvailabilityEndpointTests public async Task ExecuteAsync_WhenBookIsAvailable_ShouldReturnSuccessJson() { // Arrange - GetBookReadingAvailabilityRequest request = _requestFixture.Create(); + GetBookReadingAvailabilityRequest request = _getBookReadingAvailabilityRequestFixture.Create(); ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true); _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(availability); @@ -62,7 +62,7 @@ public class GetReadingAvailabilityEndpointTests public async Task ExecuteAsync_WhenBookIsNotAvailable_ShouldReturnUnavailableJsonWithErrorCode() { // Arrange - GetBookReadingAvailabilityRequest request = _requestFixture.Create(); + GetBookReadingAvailabilityRequest request = _getBookReadingAvailabilityRequestFixture.Create(); ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled"); _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(availability); @@ -81,7 +81,7 @@ public class GetReadingAvailabilityEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingAvailabilityFromApi() { // Arrange - GetBookReadingAvailabilityRequest request = _requestFixture.Create(); + GetBookReadingAvailabilityRequest request = _getBookReadingAvailabilityRequestFixture.Create(); ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true); _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(availability); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs index fbae8781..29a31cf8 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -30,7 +30,7 @@ public class GetReadingManifestEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly GetReadingManifestEndpoint _sut; - private readonly GetBookReadingManifestRequestFixture _requestFixture = new(); + private readonly GetBookReadingManifestRequestFixture _getBookReadingManifestRequestFixture = new(); private readonly ReadingManifestDtoFixture _readingManifestDtoFixture = new(); private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); @@ -47,7 +47,7 @@ public class GetReadingManifestEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithManifest() { // Arrange - GetBookReadingManifestRequest request = _requestFixture.Create(); + GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create(); ReadingManifestDto manifest = _readingManifestDtoFixture.Create(); _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(manifest); @@ -66,7 +66,7 @@ public class GetReadingManifestEndpointTests public async Task ExecuteAsync_WhenApiReturnsNoReaderAvailable_ShouldReturnDistinctErrorCodeJson() { // Arrange - GetBookReadingManifestRequest request = _requestFixture.Create(); + GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create(); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "NoReaderAvailable"), HttpStatusCode.NotFound)); @@ -84,7 +84,7 @@ public class GetReadingManifestEndpointTests public async Task ExecuteAsync_WhenApiReturnsReaderDisabled_ShouldReturnDistinctErrorCodeJson() { // Arrange - GetBookReadingManifestRequest request = _requestFixture.Create(); + GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create(); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "ReaderDisabled"), HttpStatusCode.NotFound)); @@ -102,7 +102,7 @@ public class GetReadingManifestEndpointTests public async Task ExecuteAsync_WhenApiReturnsUnrelatedError_ShouldRethrow() { // Arrange - GetBookReadingManifestRequest request = _requestFixture.Create(); + GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create(); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "BookNotFound"), HttpStatusCode.NotFound)); @@ -117,7 +117,7 @@ public class GetReadingManifestEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingManifestFromApi() { // Arrange - GetBookReadingManifestRequest request = _requestFixture.Create(); + GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create(); ReadingManifestDto manifest = _readingManifestDtoFixture.Create(); _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(manifest); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index 4e9cb830..cd42f941 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -26,7 +26,7 @@ public class GetReadingResourceEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly GetReadingResourceEndpoint _sut; - private readonly GetBookReadingResourceRequestFixture _requestFixture = new(); + private readonly GetBookReadingResourceRequestFixture _getBookReadingResourceRequestFixture = new(); private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); /// @@ -42,7 +42,7 @@ public class GetReadingResourceEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnBytesResultWithResourceData() { // Arrange - GetBookReadingResourceRequest request = _requestFixture.Create(); + GetBookReadingResourceRequest request = _getBookReadingResourceRequestFixture.Create(); BlobDataDto blob = _blobDataDtoFixture.Create(contentType: "image/png"); _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) .Returns(blob); @@ -60,7 +60,7 @@ public class GetReadingResourceEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingResourceFromApi() { // Arrange - GetBookReadingResourceRequest request = _requestFixture.Create(); + GetBookReadingResourceRequest request = _getBookReadingResourceRequestFixture.Create(); BlobDataDto blob = _blobDataDtoFixture.Create(); _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) .Returns(blob); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index 81f0bb18..f48a253b 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -27,7 +27,7 @@ public class GetReadingSectionEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly GetReadingSectionEndpoint _sut; - private readonly GetBookReadingSectionRequestFixture _requestFixture = new(); + private readonly GetBookReadingSectionRequestFixture _getBookReadingSectionRequestFixture = new(); private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new(); /// @@ -43,7 +43,7 @@ public class GetReadingSectionEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithSection() { // Arrange - GetBookReadingSectionRequest request = _requestFixture.Create(); + GetBookReadingSectionRequest request = _getBookReadingSectionRequestFixture.Create(); ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: request.LocationRef); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(section); @@ -62,7 +62,7 @@ public class GetReadingSectionEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingSectionFromApi() { // Arrange - GetBookReadingSectionRequest request = _requestFixture.Create(); + GetBookReadingSectionRequest request = _getBookReadingSectionRequestFixture.Create(); ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: request.LocationRef); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(section); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs index 9f7ac7b5..7146ef2e 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs @@ -21,7 +21,7 @@ namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenConten public class ReadViewEndpointTests { private readonly ReadViewEndpoint _sut = Factory.Create(); - private readonly ReadBookViewRequestFixture _requestFixture = new(); + private readonly ReadBookViewRequestFixture _readBookViewRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -36,7 +36,7 @@ public class ReadViewEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldReturnTheReadRazorView() { // Arrange - ReadBookViewRequest request = _requestFixture.Create(); + ReadBookViewRequest request = _readBookViewRequestFixture.Create(); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj index 850fd87a..3045e5bf 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - false true